Use std::merge to merge elements in two elements into the third one in sorted order
#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
int a1[ 5 ] = { 1, 3, 5, 7, 9 };
int a2[ 5 ] = { 2, 4, 5, 7, 9 };
std::vector< int > v1( a1, a1 + 5 );
std::vector< int > v2( a2, a2 + 5 );
std::ostream_iterator< int > output( cout, " " );
std::copy( v1.begin(), v1.end(), output ); // display vector output
cout << "\n\n";
std::copy( v2.begin(), v2.end(), output ); // display vector output
std::vector< int > results2( v1.size() + v2.size() );
std::merge( v1.begin(), v1.end(), v2.begin(), v2.end(), results2.begin() );
cout << "\n\nAfter merge of v1 and v2 results2 contains:\n";
std::copy( results2.begin(), results2.end(), output );
cout << endl;
return 0;
}
/*
1 3 5 7 9
2 4 5 7 9
After merge of v1 and v2 results2 contains:
1 2 3 4 5 5 7 7 9 9
*/
Related examples in the same category