1.头文件:include<queue>
2.定义:优先队列和队列一样,只能从队尾插入元素,从队首删除元素。队列中最大的元素总是位于队首。可以通过重载<运算符来重新定义比较规则。
3.优点:自动排序
4.声明:priority_queue<数据类型> 队列名;
5.常用的声明:
5.1基本常量的优先队列:
priority_queue q1;priority_queueq2;
5.2常用的优先队列:
priority_queue5.3自定义结构体优先队列,greater > q;//使元素按照从小到大顺序出队 priority_queue ,less > q2;//降序排列 ,无需声明vector头文件
#include#include using namespace std;struct Node{ int id; int x;}; bool operator < (const Node &a,const Node &b){ return a.id q; return 0;}
6.常用操作:
empty() 如果队列为空,则返回真
pop() 删除队列第一个元素
push() 加入一个元素
size() 返回队列的元素个数
top() 取队顶元素
7.测试代码:
#include#include using namespace std;struct Node{ int id; int x; Node (int id,int x):id(id),x(x){} void print(){ cout << id << " " << x << endl; }}; bool operator < (const Node &a,const Node &b){ return a.id < b.id;}int main(){ priority_queue q; int id,x; do{ cin >> id >> x; q.push(Node(id,x)); }while(id != 0); while(!q.empty()){ Node a = q.top(); q.pop(); a.print(); } return 0;}