merge
//版本一:用operator <比较元素 template <class InputerIterator1,class InputerIterator2,class OutputIterator> OutputIterator merge(InputerIterator1 first1,InputerIterator1 last1, InputerIterator2 first2,InputerIterator2 last2, OutputIterator result); //版本二:用自定义的function object比较元素 template <class InputerIterator1,class InputerIterator2,class OutputIterator,class StrictWeakOrdering> OutputIterator merge(InputerIterator1 first1,InputerIterator1 last1, InputerIterator2 first2,InputerIterator2 last2, OutputIterator result,StrictWeakOrdering cmp);
- 把两个已排序的ranges合并成单一的一个range,若两个input range有等价(相同)的元素,第一个range的排在第二个range的之前,稳定的,元素相对位置不改变
- [first1,last1)和[result,result+(last1-first1)+(last2-first2))不重叠 ,合并后的长度等于两个range长度之和
- [first2,last2)和[result,result+(last1-first1)+(last2-first2))不重叠
inplace_merge
//版本一:用operator <比较元素 template <class BidirectionalIterator> inline void inplace_merge(BidirectionalIterator first,BidirectionalIterator middle,BidirectionalIterator last); //版本二:用自定义的function object比较元素 template <class BidirectionalIterator,class StrictWeakOrdering> inline void inplace_merge(BidirectionalIterator first,BidirectionalIterator middle,BidirectionalIterator last,StrictWeakOrdering cmp);
把两段已连接的分别排序的合成一个排序的range,两段递增的range合并成一个递增的range,range中的相对元素也不会改变,此算法会分配临时内存缓冲区,运行速度取决于多少内存可用
#include <iostream> #include <vector> #include <iterator> #include <algorithm> using namespace std; int main() { vector<int> v{1,3,5,7,9}; vector<int> v1{2,4,6,8,8,10}; merge(v.begin(),v.end(),v1.begin(),v1.end(),ostream_iterator<int>(cout," ")); cout<<endl; vector<int> v2{10,16,19,3,6,9}; inplace_merge(v2.begin(),v2.begin()+3,v2.end()); for_each(v2.begin(),v2.end(),[](int i) { cout<<i<<" "; }); cout<<endl; return 0; }