priority_queue又称为优先队列,其底层是用堆(heap)来实现的
在优先队列中,队首元素是当前队列中优先级最高的一个
1、priority_queue的定义
#include <queue>
using namespace std;
queue<typename> name;
2、priority_queue容器内元素的访问
和队列不一样,优先队列没有front()、back()函数,
只能通过top()函数来访问队首元素(堆顶元素),也就是优先级最高的元素
3、priority_queue常用函数实例解析
(1)push()
push(x)将x入队,时间复杂度O(log N),其中N为当前优先队列中元素的个数
(2)top()
top()可以获得队首元素,时间复杂度O(log N)
(3)pop()
pop()令队首元素出队,时间复杂度O(log N)
(4)empty()
empty检测priority_queue是否为空,为空返回true,不空返回false,时间复杂度O(1)
(5)size()
size()返回priority_queue内元素的个数,时间复杂度O(1)
4、priority_queue内元素优先级的设置(重点)
(1)基本数据类型的优先级设置
在这里指的基本数据类型是int, char, double可以直接使用的数据类型
默认是数值越大优先级越高
priority_queue<int> q;
priority_queue<int, vector<int>, less<int>> q;码片
int表示priority_queue中存储元素的类型,vector是承载数据结构堆(heap)底层容器
less表示数字越大优先级越高
greater表示数据越小优先级越高
(2)结构体的优先级的设置
struct cmp{
bool operator()(ListNode *a, ListNode *b){
return a->val > b->val;
}
};
优先队列中cmp函数的效果和sort中cmp的效果刚好相反
notes:
如果结构体中的数据较为庞大(例如出现字符串或数组),可以使用引用来提高效率
此时在参数中加上"const"、"&"
struct cmp{
bool operator()(const ListNode *a, const ListNode *b){
return a->val > b->val;
}
}; ```