How to merge two vectors into the third vector in sorted order in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

using std::cout;
using std::endl;
using std::vector;

int main()
{
	vector<int> vec1 = { 0, 2, 4, 5 };
	vector<int> vec2 = { 1, 3, 5, 6 };
	std::ostream_iterator<int> output(cout, " ");
	vector<int> results(vec1.size() + vec2.size());

	std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), results.begin());

	std::copy(results.begin(), results.end(), output);

	cout << endl;

	return 0;
}

/*
run:

0 1 2 3 4 5 5 6

*/

 



answered Feb 26, 2018 by avibootz
edited Feb 27, 2018 by avibootz
0 votes
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

int main()
{
	vector<int> vec1 = { 0, 2, 4, 6, 8 };
	vector<int> vec2 = { 1, 3, 5, 7, 9 };
	vector<int> vec3(vec1.size() + vec2.size());

	merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), vec3.begin());

	for (int i = 0; i < 10; i++)
		cout << vec3[i] << ' ';

	cout << endl;

	return 0;
}

/*
run:

0 1 2 3 4 5 6 7 8 9

*/

 



answered Mar 3, 2018 by avibootz
...