Vectors And Merging - c++

For this vectors and merging assignment, we are supposed to read in user inputted strings and sort them alphabetically. I got the first two parts, but when I am putting the sorted elements in the new vector, it says that my new vector is out of range. Does anyone know how to fix this?
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> que1;
vector<string> que2;
vector<string> que_merge;
string firstName;
string secondName;
int counterq1 = 0;
int counterq2 = 0;
cout << "Enter queues: " << endl;
bool check = true;
while(check) {
cin >> firstName;
if (firstName == "ENDQ"){
check = false;
}
else{
que1.push_back(firstName);
counterq1++;
check = true;
}
}
// que1.resize(counterq1);
bool check2 = true;
while (check2) {
cin >> secondName;
if (secondName == "ENDQ") {
check2 = false;
} else {
que2.push_back(secondName);
counterq2++;
}
}
// que2.resize(counterq2);
cout << "que1: " << counterq1 << endl;
for (int i = 0; i < que1.size(); i++) {
cout << que1.at(i) << endl;
}
cout << endl;
cout << "que2: " << counterq2 << endl;
for (int j = 0; j < que2.size(); j++) {
cout << que2.at(j) << endl;
}
cout << endl;
cout << "que_merge: " << counterq1 + counterq2 << endl;
int i = 0;
int k = 0;
int j = 0;
while (1){
if (i >= counterq1 || j >= counterq2){
break;
}
if(que1.at(i) < que2.at(j)){
que_merge.push_back(que1.at(i));
i++;
}
else{
que_merge.push_back(que2.at(j));
j++;
}
k++;
}
if (que1.empty()){
for (int m = j; m < counterq2; m++){
que_merge.push_back(que2.at(m));
}
} else {
for (int l = i; l < counterq1; ++l) {
que_merge.push_back(que1.at(l));
}
}
for (int l = 0; l < (counterq1+counterq2); l++) {
cout << que_merge.at(l) << endl;
}
return 0;
}

I think your problem is that these lines:
if (que1.empty()){
for (int m = j; m < counterq2; m++){
que_merge.push_back(que2.at(m));
}
} else {
for (int l = i; l < counterq1; ++l) {
que_merge.push_back(que1.at(l));
}
}
doesn't do what you expect.
As far as I can see, your idea is to merge the remaining element from either que1 or que2.
However, that is not what you get from this code as the elements in que1 and que2 is never erased. In other words - the check for an empty queue is rather meaningless and you can't be sure that all elements are added to que_merge
So when you do:
for (int l = 0; l < (counterq1+counterq2); l++) {
cout << que_merge.at(l) << endl;
}
you may read beyond the number of elements in que_merge
Tip:
Don't count the number of elements your self. Use size() (like que_merge.size()) instead. For instance:
for (int l = 0; l < que_merge.size(); l++) {
cout << que_merge.at(l) << endl;
}
or a range based loop like:
for (const auto& s : que_merge) {
cout << s << endl;
}

#include <algorithm>
Use std::merge and std::sort, not necessarily in that order.
If the assignment says you can't do it the C++ way, that you have to write it all out, you can do it the engineer's way: Find an example that works, and crib it.
There are two possible implementations of std::merge on this page: All about C++ merge

Related

Display first even and then odd elements in a C++array

I'm a C++ newb. I need to insert numbers to an array and then display first the odd numbers and then the even numbers in a single array. I've managed to create two separate arrays with the odd and even numbers but now I don't know how to sort them and put them back in a single array. I need your help to understand how to do this with basic C++ knowledge, so no advanced functions. Here's my code:
#include <iostream>
using namespace std;
int main()
{
int N{ 0 }, vector[100], even[100], odd[100], unify[100], i{ 0 }, j{ 0 }, k{ 0 };
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++) {
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++) {
if (vector[i] % 2 == 0) {
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0) {
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++) {
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++) {
cout << " " << odd[i] << " ";
cout << endl;
}
return 0;
}
If you don't need to store the values then you can simply run through the elements and print the odd and the even values to different stringstreams, then print the streams at the end:
#include <sstream>
#include <stddef.h>
#include <iostream>
int main () {
std::stringstream oddStr;
std::stringstream evenStr;
static constexpr size_t vecSize{100};
int vec[vecSize] = {10, 5, 7, /*other elements...*/ };
for(size_t vecIndex = 0; vecIndex < vecSize; ++vecIndex) {
if(vec[vecIndex] % 2 == 0) {
evenStr << vec[vecIndex] << " ";
} else {
oddStr << vec[vecIndex] << " ";
}
}
std::cout << "Even elements are:" << evenStr.rdbuf() << std::endl;
std::cout << "Odd elements are:" << oddStr.rdbuf() << std::endl;
}
Storing and sorting the elements are always expensive.
Basically, it would be better to sort them first.
#include <iostream>
using namespace std;
int main()
{
int numbers[5];
int mergedArrays[5];
int evenNumbers[5];
int oddNumbers[5];
for(int i=0;i<5;i++){
cin>>numbers[i];
}
int temp=numbers[0];
//bubble sort
for(int i = 0; i<5; i++)
{
for(int j = i+1; j<5; j++)
{
if(numbers[j] < numbers[i])
{
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
int nEvens=0;
int nOdds=0;
for(int i = 0; i<5; i++)
{
if(numbers[i]%2==0)
{
evenNumbers[nEvens]=numbers[i];
nEvens++;
}
else if(numbers[i]%2!=0)
{
oddNumbers[nOdds]=numbers[i];
nOdds++;
}
}
int lastIndex=0;
//copy evens
for(int i = 0; i<nEvens; i++)
{
mergedArrays[i]=evenNumbers[i];
lastIndex=i;
}
//copy odds
for(int i =lastIndex; i<nOdds; i++)
{
mergedArrays[i]=oddNumbers[i];
}
return 0;
}
If you have to just output the numbers in any order, or the order given in the input then just loop over the array twice and output first the even and then the odd numbers.
If you have to output the numbers in order than there is no way around sorting them. And then you can include the even/odd test in the comparison:
std::ranges::sort(vector, [](const int &lhs, const int &rhs) {
return ((lhs % 2) < (rhs % 2)) || (lhs < rhs); });
or using a projection:
std::ranges::sort(vector, {}, [](const int &x) {
return std::pair<bool, int>{x % 2 == 0, x}; });
If you can't use std::ranges::sort then implementing your own sort is left to the reader.
I managed to find the following solution. Thanks you all for your help.
#include <iostream>
using namespace std;
int main()
{
int N{0}, vector[100], even[100], odd[100], merge[100], i{0}, j{0}, k{0}, l{0};
cout << "Add the dimension: " << endl;
cin >> N;
cout << "Add the elements: " << endl;
for (int i = 0; i < N; i++)
{
cout << "v[" << i << "]=" << endl;
cin >> vector[i];
}
for (i = 0; i < N; i++)
{
if (vector[i] % 2 == 0)
{
even[j] = vector[i];
j++;
}
else if (vector[i] % 2 != 0)
{
odd[k] = vector[i];
k++;
}
}
cout << "even elements are :" << endl;
for (i = 0; i < j; i++)
{
cout << " " << even[i] << " ";
cout << endl;
}
cout << "Odd elements are :" << endl;
for (i = 0; i < k; i++)
{
cout << " " << odd[i] << " ";
cout << endl;
}
for (i = 0; i < k; i++)
{
merge[i] = odd[i];
}
for (int; i < j + k; i++)
{
merge[i] = even[i - k];
}
for (int i = 0; i < N; i++)
{
cout << merge[i] << endl;
}
return 0;
}
You can use Bubble Sort Algorithm to sort whole input. After sorting them using if and put odd or even numbers in start of result array and and others after them. like below:
//Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
// Last i elements are already
// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
// Insert In array
int result[100];
if(odd[0]<even[0])
{
for (int i = 0; i < k; i++)
{result[i] = odd[i];}
for (int i = 0; i < j; i++)
{result[i+k] = even[i];}
}else
{
for (int i = 0; i < j; i++)
{result[i] = even[i];}
for (int i = 0; i < k; i++)
{result[i+k] = odd[i];}
}

How to print a message one time after all the iterations in the loop "for" are done?

My program analyzes the array in the loop "for". If all elements satisfy the condition, it should print a message one time, but my program does it after each iteration.
Here's my code:
#include <iostream>
using namespace std;
int main()
{
const int size = 32;
int ARR[size];
cout << "The size of the set is " << size << " elements." << endl << endl;
cout << "Enter the elements of the set: ";
for (int i = 0; i < size; i++)
{
cin >> ARR[i];
}
for (int i = 0; i < size; i++)
{
if (ARR[i] > ARR[i])
cout << "\nThe relation is reflexive." << endl;
else
cout << "\nThe relation is not reflexive." << endl;
}
return 0;
}
I need that message to be printed after all the iterations are done. How can I achieve that result?
It's pretty easy, just use a boolean flag to determine if the condition is met:
bool isReflexive = true;
for (int i = 0; i < size; i++) {
if (ARR[i] <= ARR[i]) {
isReflexive = false;
break;
}
}
if(isReflexive)
cout << "\nThe relation is reflexive." << endl;
else
cout << "\nThe relation is not reflexive." << endl;
Note: The code above will always set isReflexive to false. You also need to compare two different indices:
for (int i = 1; i < size; i++) {
if (ARR[i-1] <= ARR[i]) { // Or whatever the correct comparison is
isReflexive = false;
break;
}
}
I would suggest to separate analysis of "reflexiveness" from printing the result. That would allow you to simply end the loop as soon as negative result is determined:
#include <iostream>
using namespace std;
bool IsReflexive(int a[], int size)
{
for (int i = 0; i < size; i++)
{
if (a[i] > a[i]) // TODO: correct this!!!
return false;
}
return true;
}
int main()
{
const int size = 32;
int ARR[size];
cout << "The size of the set is " << size << " elements." << endl << endl;
cout << "Enter the elements of the set: ";
for (int i = 0; i < size; i++)
{
cin >> ARR[i];
}
if (IsReflexive(ARR, size))
cout << "\nThe relation is reflexive." << endl;
else
cout << "\nThe relation is not reflexive." << endl;
return 0;
}

Hi, i have a problem with this code. ODD and EVEN numbers

I have a problem with this piece of code, I'm trying to print the EVEN and ODD numbers, but there is a problem when it comes to show them, the vectors don't save the numbers as I'm expecting.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n]; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[i] = vect[i]; // I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[i] == vect[i];
}
}
for(int i = 1; i <= n; ++i) {
cout << even[i] << " " << endl; /// PRINTING THE ODD AND EVEN numbers.
cout << odd[i] << " " << endl;
}
return 0;x
}
I have fixed the problem, thanks all for help.
Now it works perfectly.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n], z = 0, x = 0; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[1+z] = vect[i];
z++;
// I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[1+x] = vect[i];
x++;
}
}
for(int i = 1; i <= x; i++) {
cout << even[i] << " ";
}
cout << endl;
for(int i = 1; i <= z; i++) {
cout << odd[i] << " ";
}
return 0;
}
Considering the hints of the comments, your program shall be changed into this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, number;
cin >> n;
vector<int> vect, even, odd; // CREATING DYNAMIC VECTORS
for(int i = 0; i < n; ++i) { // ENTERING THE ELEMENTS IN VECTOR
cin >> number;
vect.push_back(number);
}
for(int i = 0; i < n; ++i) {
if(vect[i] % 2 != 0) { /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
odd.push_back(vect[i]);
}
else {
even.push_back(vect[i]);
}
}
for (int i = 0; i < n; ++i)
cout << vect[i] << " ";
cout << endl;
/// PRINTING THE ODD AND EVEN NUMBERS.
for (auto& val : odd)
cout << val << " ";
cout << endl;
for (auto& val : even)
cout << val << " ";
cout << endl;
return 0;
}
It uses the vector container of STL for your arrays, start the indexing at 0 and prints out the resulting arrays separately, as the number of odd and of even entries might be different.
Hope it helps?
With standard, you might use std::partition (or stable version) to solve your problem:
void print_even_odd(std::vector<int> v)
{
auto limit = std::stable_partition(v.begin(), v.end(), [](int n){ return n % 2 == 0; });
std::cout << "Evens:";
// Pre-C++20 span:
// for (auto it = v.begin(); it != limit; ++it) { int n = *it;
for (int n : std::span(v.begin(), limit)) {
std::cout << " " << n;
}
std::cout << std::endl;
std::cout << "Odds:";
for (int n : std::span(limit, v.end())) {
std::cout << " " << n;
}
std::cout << std::endl;
}
Demo

C++ Integer Array Palindrome Checker

I used the following code for palindrome check of an integer array and used the value of variable 'declare' as check of palindrome. I used the technique that if declare is 1 at the end, array is palindrome, else not. But its not working. In the end of code, it always keeps the value of declare which was initialized, independent of rest of the code. Please Debug.
#include <iostream>
using namespace std;
void main()
{
int array1[3] = {0,0,1};
int j = 2;
cout << "Given Array is:\n";
for (int i = 0; i < 3; i++)
cout << array1[i];
cout << endl;
int determiner[3];
for (int i = 0; i <3; i++){
determiner[j] = array1[i];
j -= 1;
}
cout << "Reversed Array is:\n";
for (int i = 0; i < 3; i++)
cout << determiner[i];
cout << endl;
int declare;
for (int u = 0; u < 3; u++)
{
if (array1[u] = determiner[u])
{
declare = 1;
}
if (array1[u] != determiner[u])
{
declare = 0;
break;
}
}
cout << endl;
cout << declare<< endl;
if (declare==1)
cout << "Given Array is Palindrome. Cheers!!!\n";
if (declare==0)
cout << "Emhmm! This aint Palindrome.\n";
system("pause");
}
if (array1[u] = determiner[u])
should be
if (array1[u] == determiner[u])

Bubble Sort Display

#include <iostream>
#include <string>
using namespace std;
void bubbleSort(int data[], int n);
int main()
{
cout << "Enter ten unsorted integers..." << endl;
int a[10];
for (int i = 0; i < 10; ++ i)
{
cout << "[" << i << "] = ";
cin >> a[i];
}
cout << endl << "Unsorted List = ";
for (int i = 0; i < 10; ++i)
cout << a[i] << ", ";
cout << endl;
cout << "Sorting..." << endl;
cout << "Sorted List = ";
bubbleSort(a, 10);
}
void bubbleSort(int data[], int n)
{
int j = 0;
bool nextEnd = true;
while (nextEnd)
{
nextEnd = false;
++j;
for (int i = 0; i < n - j; ++i)
{
if (data[i] > data[i+1])
{
int temp = data[i];
data[i] = data[i+1];
data[i+1] = data[i];
nextEnd = true;
}
}
}
for (int i = 0; i < 10; ++i)
cout << data[i] << ", ";
}
The program is really simple. Input ten values to an array. Display them unsorted. Send them into the bubbleSort function, sort them and finally display the sorted list. The problem I'm having is I don't get the outputting back to work. I tested with the last line of code but that doesn't work. I don't think my sorting is messed up either. How can I display this sorted list properly?
There is at least one error in the bubble sort. The assignment to data[i+1] is not correct. It should be:
data[i+1] = temp;
The problem is your 'swap'. It should be:
int temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
Edit-Tested and works fine with the correction.