STL中合并算法merge介绍,merge与inplace_merge。
merge合并两个有序的sequence,默认为<比较,可自定义比较函数comp,结果保存在[result, result + (last1 - first1) + (last2 - first2))
中。函数定义如下:
OutputIterator merge (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result)
OutputIterator merge (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
inplace_merge合并一个中前后两段分别有序的序列,即[first,middle)与[middle,last)分别有序,合并这两个子序列,并把结果保存在[first,last)中。
inplace_merge (BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last);
inplace_merge (BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp);
#include<string>
#include<algorithm>
#include<iostream>
#include<iterator>
#include<vector>
using namespace std;
int main()
{
vector<int>v1;
vector<int>v2;
vector<int>v3;
vector<int>::iterator vecitr;
for(int i = 1; i <= 10; i++){
v1.push_back(i%7);
v2.push_back(i%4);
}
sort(v1.begin(),v1.end());
cout << "Fisrt vecter: ";
copy(v1.begin(),v1.end(),ostream_iterator<int>(cout," "));
cout << endl << endl;
sort(v2.begin(),v2.end());
cout << "Second vecter: ";
copy(v2.begin(),v2.end(),ostream_iterator<int>(cout," "));
cout << endl << endl;
cout << "Merge this two vecter: ";
merge(v1.begin(),v1.end(),v2.begin(),v2.end(),ostream_iterator<int>(cout," "));
cout << endl << endl;
for(int i = 1; i <= 10; i++){
v3.push_back(i%7);
}
sort(v3.begin(),v3.end());
int x = v3.size();
for(int i = 1; i <= 10; i++){
v3.push_back(i%4);
}
vecitr = v3.begin();
advance(vecitr,x);
sort(vecitr,v3.end());
cout << "Third vecter: ";
copy(v3.begin(),v3.end(),ostream_iterator<int>(cout," "));
cout << endl << endl;
cout << "inplace_Merge third vecter: ";
inplace_merge(v3.begin(),vecitr,v3.end());
copy(v3.begin(),v3.end(),ostream_iterator<int>(cout," "));
cout << endl << endl;
return 0;
}
Fisrt vecter: 0 1 1 2 2 3 3 4 5 6
Second vecter: 0 0 1 1 1 2 2 2 3 3
Merge this two vecter: 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 5 6
Third vecter: 0 1 1 2 2 3 3 4 5 6 0 0 1 1 1 2 2 2 3 3
inplace_Merge third vecter: 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 5 6