merge() algorithm function is used to merge the data(or)elements of two container's.
Definition:
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
template <class InputIterator1, class InputIterator2,class OutputIterator, class Compare>
OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result, Compare comp);
NOTE:
In this program we are merging the elements of two vector containers and storing the result in
another vector container and printing merged elements.
sort() function is used to sort the elements of both vector container's.
Executable on C++98/11.
__________________________________________________________________________
PROGRAM:
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,i,array[10],array1[10];
cout<<"Enter the size:"<<endl;
cin>>n;
cout<<"Enter the elements of container 1:"<<endl;
for(i=0;i<n;i++)
{
cin>>array[i];
}
cout<<"Enter the elements of container 2:"<<endl;
for(i=0;i<n;i++)
{
cin>>array1[i];
}
vector<int>v(array,array+n); // 1st vector container
vector<int>v1(array1,array1+n);//2nd vector container
sort(v.begin(),v.end());
sort(v1.begin(),v1.end());
vector<int>v2(2*n);//3rd vector container(result)
vector<int> :: iterator it;
merge(v.begin(),v.end(),v1.begin(),v1.end(),v2.begin());
for(it=v2.begin();it!=v2.end();++it)
{
cout<< *it <<" ";
}
}
OUTPUT:
Enter the size:
6
Enter the elements of container 1:
2
3
1
6
5
7
Enter the elements of container 2:
13
12
17
11
19
21
1 2 3 5 6 7 11 12 13 17 19 21
Comments