描述
在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素在顶部。优先队列具有最高级先出 (first in, largest out)的行为特征。
优先队列有三个参数,其声明形式为:
priority_queue< type, container, function >
这三个参数,后面两个可以省略,第一个不可以。
其中:
- type:数据类型;
- container:实现优先队列的底层容器;
- function:元素之间的比较方式;
对于container,要求必须是数组形式实现的容器,例如vector、deque,而不能使list。
成员函数
假设type类型为int,则:
- bool empty() const
返回值为true,说明队列为空; - int size() const
返回优先队列中元素的数量; - void pop()
删除队列顶部的元素,也即根节点 - int top()
返回队列中的顶部元素,但不删除该元素; - void push(int arg)
将元素arg插入到队列之中;
使用示例
#include <iostream>
#include <queue>
using namespace std;
//方法1
struct tmp1 //运算符重载<
{
int x;
tmp1(int a) {x = a;}
bool operator<(const tmp1& a) const //假想成a为后来者
{
return x < a.x; //大顶堆 满足条件直接放在后面,不满足条件就换位置
}
};
//方法2
struct tmp2 //重写仿函数
{
bool operator() (tmp1 a, tmp1 b) //假想成b为后来者
{
return a.x < b.x; //大顶堆
//return a.x > b.x; //小顶堆 满足条件直接放在后面,不满足条件就换位置
}
};
int main()
{
tmp1 a(1);
tmp1 b(2);
tmp1 c(3);
priority_queue<tmp1> d;
d.push(b);
d.push(c);
d.push(a);
while (!d.empty())
{
cout << d.top().x << '\n';
d.pop();
}
cout << endl;
priority_queue<tmp1, vector<tmp1>, tmp2> f;
f.push(b);
f.push(c);
f.push(a);
while (!f.empty())
{
cout << f.top().x << '\n';
f.pop();
}
}