merge() Function in C++

«
»
This C++ program merges two sequences using merge() algorithm. This algorithm combines the elements present in the two sorted ranges into a new range given as an argument to the merge() routine.

Here is the source code of the C++ program which merges two sequences using merge() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to merge two sequences using merge() algorithm
  3.  */
  4. #include <iostream>    
  5. #include <algorithm>   
  6. #include <vector>       
  7. using namespace std;
  8.  
  9. void printVector(vector<int>& v)
  10. {
  11.     for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
  12.         cout << ' ' << *it;
  13.     cout << '\n';
  14. }
  15.  
  16. int main () {
  17.     vector<int> v1 = {5,10,15,20,25}, v2 = {50,40,30,20,10}, v3(10);
  18.  
  19.     sort(v1.begin(), v1.end());
  20.     sort(v2.begin(), v2.end());
  21.     merge(v1.begin(),v1.end(),v2.begin(),v2.end(),v3.begin());
  22.  
  23.     cout << "Vector v1 : ";
  24.     printVector(v1);
  25.     cout << "Vector v2 : ";
  26.     printVector(v2);
  27.     cout << "Vector v3 : ";
  28.     printVector(v3);
  29. }

$ gcc test.cpp
$ a.out
Vector v1 :  5 10 15 20 25
Vector v2 :  10 20 30 40 50
Vector v3 :  5 10 10 15 20 20 25 30 40 50

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.