C++ - 标准库 "merge" 函数 的 用法及代码

标准库 "merge" 函数 的 用法及代码

 

merge() 是 C++ 标准库的函数, 主要实现函数的排序和合并, 不仅仅是合并, 具体要求参照标准库.

网址: http://www.cplusplus.com/reference/algorithm/merge/?kw=merge

如果是通用方法, 则第二个容器依然存在; 如果是链表方法, 则第二个容器被破坏, 存入第一个容器.

输入的两个序列 必须 符合谓词的要求,默认谓词是 "<"; 也可以使用自定义谓词, 例如 ">" 的函数.

由于编译器无法检查输入容器是否符合要求(符合谓词), 所以必须需要程序提前判断, 否则出错.

下面代码包含了两种方法, 一种是默认谓词, 一种是自定义谓词, 注意 输入容器的顺序.

 

代码(VS2012)

#include "stdafx.h"

#include <iostream>
#include <algorithm>
#include <array>
#include <list>

using namespace std;

bool comp(const int i, const int j){
	return i>j;
}

int main(void) {
	/*自定义谓词*/
	std::array<int, 4> ai1 = {1, 3, 4, 5};
	std::list<int> lsti1;
	for(const auto& i : ai1)
		lsti1.push_front(i); //从大到小
	std::array<int, 4> ai2 = {2, 6, 7, 8};
	std::list<int> lsti2;
	for(const auto& i : ai2)
		lsti2.push_front(i);

	lsti1.merge(lsti2, comp);

	std::cout << "merge(>) : ";
	for(const auto& i : lsti1)
		std::cout << i << " ";
	std::cout << std::endl;

	/*默认谓词*/
	std::array<int, 4> ai1d = {1, 3, 4, 5};
	std::list<int> lsti1d;
	for(const auto& i : ai1d)
		lsti1d.push_back(i); //从小到大
	std::array<int, 4> ai2d = {2, 6, 7, 8};
	std::list<int> lsti2d;
	for(const auto& i : ai2d)
		lsti2d.push_back(i);

	lsti1d.merge(lsti2d);

	std::cout << "merge(<) : ";
	for(const auto& i : lsti1d)
		std::cout << i << " ";
	std::cout << std::endl;

	return 0;

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值