In: Computer Science
Create a function called merge that takes two int vectors (x and y) as argument and returns an int vector (z) that is the result of merging the two vectors x and y. Here is an example to explain how the merge function works: If the vector x has the following values: 1 2 3 4 5, and the vector y has the following: 6 7 8 9 10 11 12, then the merging vector z will have: 1 6 2 7 3 8 4 9 5 10 11 12. This means: z[0] = x[0], z[1]=y[0], z[2]=x[1], z[3]=y[1], z[4]=x[2], z[5]=y[2],... If the size of the vector x is bigger than the size of the vector y, when x is entirely copied to z, the rest of x will be copied next. If y is bigger, the rest of y is copied when x is entirely copied to z.
Language: c++
Below is the complete C++ code. If you face any difficulty while understanding the solution, Please let me know in the comments.
Code:
#include <iostream>
#include <vector>
using namespace std;
vector<int> merge(vector<int> x, vector<int>
y) {
vector<int> z;
// get the size of both the vectors
int size1 = x.size(), size2 = y.size();
int i = 0, j = 0;
// loop while both the vectors are not traversed completely
while(i < size1 || j < size2) {
// add current item from x vector
if(i < size1) {
z.push_back(x[i]);
i++;
}
// add currentitem from y vector
if(j < size2) {
z.push_back(y[j]);
j++;
}
}
return z;
}
int main() {
vector<int> x = { 1, 2, 3, 4, 5 };
vector<int> y = { 6, 7, 8, 9, 10, 11, 12};
// call merge function
vector<int> z = merge(x,y);
// print the items of merged vector
for (auto& iterator : z)
cout << iterator << ' ';
return 0;
}
Screenshots:
Output: