C++ priority_queue使用Lambda表达式重写compartor

在之前的blog中介绍过STL库中set、map、priority_queue三种排序方式,那么相信读者会经常用到特殊的type,这时,我们需要重写compartor,举个栗子

以Pair中第二个元素构建大根堆

	auto cmp = [](const pair<int, int> &a, const pair<int, int> &b) {
		return a.second < b.second;//less
	};
	priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)>q(cmp);

注意:
q(cmp);因为lambda这种特殊的class没有默认构造函数,priority_queue内部排序比较的时候要使用的是一个实例化的lambda对象,只能通过lambda的 copy构造进行实例化,从哪里copy呢,就需要priority_queue构造函数的时候传入这个lambda对象。priority_queue的自定义比较也可以使用struct或者class,因为struct和class都有默认构造函数,此时就不需要pq(Type) 而是直接pq即可。同理,自定义比较也可以使用函数,同样此时也需要提供函数对象进行实例化pq(CmpFunc),假设比较函数为bool CmpFunc(int x, int y) {return x < y;}
同理,若想要构建小根堆,则只需将lambda表达式中的比较条件更改即可

以Pair中第二个元素构建小根堆

	auto cmp = [](const pair<int, int> &a, const pair<int, int> &b) {
		return a.second > b.second;//greater
	};
	priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)>q(cmp);

除此以外,我们还可以使用仿函数(函数对象),在这里仅给出小根堆

class compare {
public:
	bool operator()(const pair<int, int> &a, const pair<int, int> &b) {
		return a.second > b.second;//greater
	}
};
priority_queue<pair<int, int>, vector<pair<int, int>>, compare>q;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值