Vector append & merge

For one way to do these, consider:

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
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>

std::vector<int> append(const std::vector<int>& v1, const std::vector<int>& v2)
{
	std::vector<int> nv(v1);

	std::copy(v2.begin(), v2.end(), std::back_inserter(nv));
	return nv;
}

std::vector<int> merge(const std::vector<int>& v1, const std::vector<int>& v2)
{
	std::vector<int> nv;

	auto it1 {v1.begin()};
	auto it2 {v2.begin()};

	for (; it1 != v1.end() && it2 != v2.end(); nv.push_back(*it1++), nv.push_back(*it2++));
	for (; it1 != v1.end(); nv.push_back(*it1++));
	for (; it2 != v2.end(); nv.push_back(*it2++));

	return nv;
}

int main()
{
	const std::vector<int> a {1, 4, 9, 16};
	const std::vector<int> b {9, 7, 4, 9, 11};

	const auto nva {append(a, b)};

	for (const auto& v : nva)
		std::cout << v << ' ';

	std::cout << "\n\n";

	const auto nvm {merge(a, b)};

	for (const auto& v : nvm)
		std::cout << v << ' ';

	std::cout << '\n';
}


Which displays:


1 4 9 16 9 7 4 9 11

1 9 4 7 9 4 16 9 11

Last edited on
@OP. Please don't delete posts. It makes my reply above out of context.

The original question was regards to concatenating 2 vectors and merging 2 vectors alternatively.
Last edited on
OPs can't delete their own posts after being replied to. Someone else did it. I don't know what the content of said post was, so I don't know if it was justified.
Last edited on
Topic archived. No new replies allowed.