Merge two sequences with algorithm merge - C++ STL Algorithm

C++ examples for STL Algorithm:merge

Description

Merge two sequences with algorithm merge

Demo Code

#include <iostream> 
#include <algorithm> // algorithm definitions 
#include <vector> // vector class-template definition 
#include <iterator> // ostream_iterator 
using namespace std; 

int main() //  ww  w  .  j a  va 2 s .co  m
{ 
   const int SIZE = 5; 
   int a1[ SIZE ] = { 1, 3, 5, 7, 9 }; 
   int a2[ SIZE ] = { 2, 4, 5, 7, 9 }; 
   
   vector< int > v1( a1, a1 + SIZE ); // copy of a1 
   vector< int > v2( a2, a2 + SIZE ); // copy of a2 
   ostream_iterator< int > output( cout, " " ); 

   cout << "Vector v1 contains: "; 
   copy( v1.begin(), v1.end(), output ); // display vector output 
   cout << "\nVector v2 contains: "; 
   copy( v2.begin(), v2.end(), output ); // display vector output 

   vector< int > results2( v1.size() + v2.size() ); 

   // merge elements of v1 and v2 into results2 in sorted order 
   merge( v1.begin(), v1.end(), v2.begin(), v2.end(), results2.begin() ); 

   cout << "\n\nAfter merge of v1 and v2 results2 contains:\n"; 
   copy( results2.begin(), results2.end(), output ); 

}

Result


Related Tutorials