priority_queue优先队列的用法


以下代码来源:晴神《算法笔记》!!

优先队列的队首元素是当前队列中优先级最高的。
使用优先队列需添加头文件queue。

定义

priority_queue<typename> name;

对元素的访问

没有队列的front()和back()函数,只可以通过top()访问队首元素。

常用函数

  • push()
  • top()
  • pop()
  • empty()
  • size()

设置优先级

  • 基本数据类型
    优先队列对基本数据类型的优先级设置默认为数字越大(字典序越大)优先级越高,其实priority_queue< int > q;的写法与下面这种写法等价:
priority_queue<int, vector<int>, less<int> > q;      //两个>之间有空格

less< int > 的意思是数字大的优先级高,因此想要让数字小的优先级高只需要改成greater< int >。

  • 结构体
    基本思想是重载“<”,重载“>”会编译错误 。
struct fruit{
	string name;
	int price;
	friend bool operator < (fruit a, fruit b){
		return a.price < b.price;   //价格高的优先级高 
	}
};

struct fruit{
	string name;
	int price;
	friend bool operator < (fruit a, fruit b){
		return a.price > b.price;   //价格低的优先级高 
	}
};

priority_queue<fruit> q; 

还有一种写法,可以像cmp函数一样写在外面。

struct cmp{
	//把friend去掉,把<改成一对() 
	bool operator () (fruit a, fruit b){
		return a.price > b.price;
	}
};
//这时优先队列要用第二种定义方法
priority_queue<fruit, vector<fruit>, cmp> q; 

如果结构体内数据比较庞大(比如出现字符串或者数组),最好在比较的参数前加上“const”和“&”,即“const fruit &a”。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值