以下代码来源:晴神《算法笔记》!!
优先队列的队首元素是当前队列中优先级最高的。
使用优先队列需添加头文件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”。