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






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

1.Use merge with back_inserter
2.Merge two containers
3.sum the ranges by using merge()
4.Demonstrating the generic merge algorithm with an array, a list, and a deque
5.Generic merge algorithm: merge parts of an array and a deque, putting the result into a list
6.Merge a vector with deque
7.Merge in place
8.Merge two ranges within a vector