merging alternating vecotrs?

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;
vector<int> merge(vector<int> a, vector<int> b);
int main()
{

	const int size = 3;
	const int 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;
}
Last edited on
One way to do it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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;
}
Topic archived. No new replies allowed.