优先队列声明的基本格式是:
priority_queue<结构类型> 队列名;
priority_queue <node> q;
//node是一个结构体
//结构体里重载了‘<’小于符号
升序排列
priority_queue <int,vector<int>,greater<int> > q;
降序排列
priority_queue <int,vector<int>,less<int> > q;
//不需要#include<vector>头文件
//注意后面两个“>”不要写在一起,“>>”是右移运算符
priority_queue <int,vector<int>,less<int> >q;
用法:
q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
结构体,重载小于
struct node
{
int x,y;
bool operator < (const node & a) const
{
return x<a.x;
}
};
或者这样排序
struct cmp{//自定义优先级
bool operator()(Node a, Node b){
if(a.x == b.x) return a.y>b.y;
return a.x>b.x; }
};试试效果
#include <bits/stdc++.h>
using namespace std;
struct node
{
int x,y;
bool operator < (const node & a) const
{
return x>a.x;
}
};
priority_queue <node> q;
int main(){
int a;
for (int i=1;i<=3;i++){
cin>>a;
q.push({a,1});
}
for (int i=1;i<=3;i++){
cout<<q.top().x;
q.pop();
}
return 0;
} 输出:
cin:3 2 1
cout:1 2 3