#include <iostream>
#include <algorithm>
#include <iterator>
//Sorted Range上的合并算法
int main()
{
/************************************************************************/
//merge
/************************************************************************/
/*merge:将两个已排序的ranges合并成一个单一的有序range
merge属于稳定行为,如果两个ranges中存在等价的元素,从第一个range来的元素会排在第二个range来的元素之前
有等价的元素不会剔除,注意与set_union的区别
*/
/*
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 BinaryPredicate>
OutputIterator merge(
InputIterator1 _First1,
InputIterator1 _Last1,
InputIterator2 _First2,
InputIterator2 _Last2,
OutputIterator _Result
BinaryPredicate _Comp
);
*/
int a1[] = { 9, 1, 3, 4, 5, 8, 7 };
int a2[] = { 3, 2, 6, 7, 3, 0, 1 };
//先排序
std::stable_sort(std::begin(a1), std::end(a1));
std::stable_sort(std::begin(a2), std::end(a2));
//再合并
std::merge(std::begin(a1), std::end(a1), std::begin(a2), std::end(a2),
std::ostream_iterator<int>(std::cout, " "));
//0 1 1 2 3 3 3 4 5 6 7 7 8 9
std::cout << std::endl;
std::cout << "========================" << std::endl;
/************************************************************************/
//inplace_merge
/************************************************************************/
//inplace_merge:如果两个连接在一起的range [first,middle)和[middle,last)都已排序,那么inplace_merge可将它们结合成一个有序的range
/*
template<class BidirectionalIterator>
void inplace_merge(
BidirectionalIterator _First,
BidirectionalIterator _Middle,
BidirectionalIterator _Last
);
template<class BidirectionalIterator, class Predicate>
void inplace_merge(
BidirectionalIterator _First,
BidirectionalIterator _Middle,
BidirectionalIterator _Last,
Predicate _Comp
);
*/
int a[] = { 1, 3, 5, 7, 2, 4, 6, 8 };
std::inplace_merge(std::begin(a), std::begin(a) + 4, std::end(a));
//1 2 3 4 5 6 7 8
std::copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
return 0;
}
====================打个广告,欢迎关注====================
QQ: | 412425870 |
csdn博客: | http://blog.youkuaiyun.com/caychen |
码云: | https://gitee.com/caychen/ |
github: | https://github.com/caychen |
点击群号或者扫描二维码即可加入QQ群: | ![]() |
![]() |