Exercise P6.5. Write a function
vector<int> merge(vector<int> a, vector<int> b)
that merges two arrays, alternating elements from both arrays. If one array is
shorter than the other, then alternate as long as you can and then append the
remaining elements from the longer array. For example, if a is
and b is
1 4 9 16
9 7 4 9 11
1 9 4 7 9 4 16 9 11
Once the shorter array has finished i can not get the program to add on the rest. Idk what to do?
#include <iostream>
#include <vector>
#include <cmath>
usingnamespace std;
vector<int> merge(vector<int> a, vector<int> b);
int main()
{
constint size = 3;
constint size2 = 4;
vector<int> a(size);
vector<int> b(size2);
float x;
float answer;
int length = size + size2;
for (int i = 0; i < a.size(); i++)
{
cout << "Enter data:" << endl;
cin >> x;
a[i] = x;
}
for (int i = 0; i < b.size(); i++)
{
cout << "Enter data:" << endl;
cin >> x;
b[i] = x;
}
merge(a, b);
return 0;
}
vector<int> merge(vector<int> a, vector<int> b)
{
vector<int> c(2);
while (c.size() < (a.size() + b.size() -1 ))
{
c.push_back(1);
}
int i = 0; // used to put in the a variables into the c vector;
int x = 0; // used for all the b variable;
int counter = 0;
do
{
if (i <= a.size())
{
c[counter] = a[i];
counter++;
i++;
}
c[counter] = b[x];
counter++;
x++;
} while (counter < c.size());
for (int i = 0; i < c.size(); i++)
{
cout << c[i] << endl;
}
return c;
}
vector<int> merge (vector<int> a, vector<int> b)
{
vector<int> result;
auto v1 = a.begin ();
auto v2 = b.begin ();
while (v1 != a.end () && v2 != b.end ())
{
result.push_back (*v1);
result.push_back (*v2);
++v1;
++v2;
}
// if both the vectors have the same size we would be finished
if (v1 != a.end ()) // v1 is the longer one
{
while (v1 != a.end ())
{
result.push_back (*v1);
++v1;
}
}
if (v2 != b.end ()) // v2 is the longer one
{
while (v2 != b.end ())
{
result.push_back (*v2);
++v2;
}
}
return result;
}