C++ priority_queue为例的比较函数

很多时候,我们需要重载诸如priority_queue中的比较函数。在这其中有一些小细节,如下:

1、经典错误及解决方案

1.1错误写法

struct node
{
public:
	node()
	{
		a = 1;
	}
	bool operator < (node b)
	{
		return a < b.a;
	}
	int a;
};

这样的比较函数在priority_queue容器中是无法通过的。
如图,转载自某某同学:
在这里插入图片描述
可以看到,里面用了const修饰。(MSVC的实现)

1.2正确示例

1.2.1示例一
struct node
{
public:
	node()
	{
		a = 1;
	}
	bool operator < (const node& b) const
	//dev中可以写bool operator < (node b) const
	{
		return a < b.a;
	}
	int a;
};
1.2.2示例二
struct cmp
{
	bool operator ()(node a , node b){
		return a.a < b.a;
	}
};

调用的时候,如下:

	priority_queue<node, vector<node>, cmp> q;

2、细节部分

如果两者同时存在,即既有在内部实现<的重载。又在外部实现 struct cmp中()的重载,并且在调用的时候两者一起调用,示例如下:

#include<bits/stdc++.h>
using namespace std;

struct node
{
public:
	node(int n)
	{
		a = n;
	}
	bool operator < ( node b) const
	{
		return a > b.a;
	}
	int a;
};

struct cmp
{
	bool operator ()(node a , node b){
		return a.a < b.a;
	}
};
int main()
{
	priority_queue<node, vector<node>, cmp> q;
	q.emplace(3);
	q.emplace(1);
	node p = q.top();
	q.pop();
	cout<<p.a<<endl;
	return 0;
}

运行结果:
在这里插入图片描述
这里,我们需要注意的是:priority_queue是从队尾弹出元素。也就是如果重载函数是要求从小到大排序,那么就会弹出最大的那个元素。
结论:在这里,我们的结论为:实际上priority_queue采用的是struct cmp中对()的重载。
具体原因不清楚,若有知情者,希望能指点指点鄙人

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值