一、priority_queue简介
- priority_queue称为优先队列,底层采用堆实现。
- 优先队列中队首元素为优先级最大的元素
- 常见用途
- 解决贪心问题,也可以对Dijkstra算法进行优化
- 注意使用top()函数前必需要用empty()判断优先队列是否为空。
二、priority_queue定义
#include<queue>
using namespace std;
priority_queue<typename> name;
三、priority_queue内元素的访问
- top():访问队首元素,即堆顶元素,也就是优先级最高的元素
四、priority_queue常用函数
- push():push(x)将x入队,时间复杂度为O(logn),n为当前优先队列中元素的个数
- top():获得队首元素,时间复杂度O(1)
- pop():令队首元素出队,时间复杂度O(logn)
- empty():检测优先队列是否为空,时间复杂度O(1)
- size():返回优先队列中元素的个数,时间复杂度O(1)
#include<stdio.h>
#include<queue>
using namespace std;
int main(){
priority_queue<int> q;
q.push(3);
q.puah(8);
q.push(1);
printf("%d\n", q.top());
q.pop();
printf("%d\n", q.top());
printf("%d\n", q.size());
return 0;
}
五、priority_queue内元素优先级的设置
- 基本数据类型的优先级设置
- 此处指的基本数据类型就是int型、double型等可以直接使用的数据类型,优先级队列对它们优先级设置一般是数字大的优先级越高,因此队首元素就是优先队列内元素最大的那个(char是字典序最大的)
- 另一种定义方式<>内有三个参数。其中,vector< int>填写的是承载底层数据结构堆的容器,如果第一个参数是double,此处只需要填写vector< double >。第三个参数less< int>是对第一个参数的比较类,less< int>表示数字大的优先级越大,而grater< int>表示数字小的优先级越大。
- 如果想让队列总是把最小的元素放在队首,只需要将第三个参数换为greater< int>
priority_queue<int> q;
priority_queue<int, vector<int>, less<int>> q;
- 结构体的优先级设置
- 通过重载<实现
- 与sort中的cmp函数有些相似,但从效果上看是相反的。在排序中,如果是return f1.price>f2.price,则价格从高到低排序。在优先队列中却是价格从低到高。
- 如果结构体内的数据比较庞大,为了减少时间可以在运算符重载时使用引用&,同时添加const表示原数据不会被修改。
#include<iostream>
#include<string>
#include<queue>
struct fruit{
string name;
int price;
friend bool operator < (fruit f1, fruit f2){
return f1.prince < f2.prince;
}f1, f2, f3;
int main(){
priority_queue<fruit> q;
f1.name = "apple";
f1.price = 3;
f2.name = "peach";
f2.price = 5;
f3.name = "melon";
f3.price = 1;
q.push(f1);
q.push(f2);
q.push(f3)l
cout<<q.top().name<<" "<<q.top().price<<endl;
return 0;
}
};