C++ STL(20):Sorted Range上的合并算法

#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群:

328243383(1群)



点击群号或者扫描二维码即可加入QQ群:

180479701(2群)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值