Use std::merge to merge elements in two elements into the third one in sorted order : merge « STL Algorithms Merge « C++ Tutorial






#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








28.3.merge
28.3.1.Use std::merge to merge elements in two elements into the third one in sorted order
28.3.2.Use merge with back_inserter
28.3.3.Merge two containers
28.3.4.sum the ranges by using merge()
28.3.5.Demonstrating the generic merge algorithm with an array, a list, and a deque
28.3.6.Generic merge algorithm: merge parts of an array and a deque, putting the result into a list