使用标准库头文件
#include<queue>
队列常用的函数
q.push(x); 向优队列添加一个元素
q.pop(); 删除队列头元素
q.front(); 返回队列头元素
q.size(); 返回队列元素个数
q.empty(); 如果优先队列为空,返回真
q.back(); 返回队列尾部首元素
优先队列常用的函数
q.push(x); 向优先队列添加一个元素
q.pop(); 删除优先队列优先级最高的元素
q.top(); 返回优先队列优先级最高的元素
q.size(); 返回优先队列元素个数
q.empty(); 如果优先队列为空,返回真
接下来主要讲优先队列的使用:
1、
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
int main()
{
priority_queue<int> q;
q.push(3);
q.push(11);
q.push(0);
q.push(7);
q.push(-1);
q.push(15);
while(!q.empty())
{
cout << q.top() << " ";
q.pop();
}
cout << endl;
return 0;
}
结果为 15 11 7 3 0 -1
如果我想让该优先队列输出小到大如何实现呢?很简单,只要将priority_queue<int> q 改成 priority_queue<int,vector<int>,greater<int>> q; 原因在于没个参数表示的含义在于:第一个表示数据类型;第二个表示保存该数据类型的容器(默认情况为vector);第三个表示自定义的优先规则(默认情况下,元素大的优先级高)。greater表示数据优先级顺序是从小到大,另外greater也可以改成less,表示数据优先级顺序是从大到小。
2、
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> > q;
q.push(3);
q.push(11);
q.push(0);
q.push(7);
q.push(-1);
q.push(15);
int len=q.size();
for(int i=0;i<len;i++)
{
cout << q.top() << " ";
q.pop();
}
cout << endl;
return 0;
}
结果为:-1 0 3 7 11 15
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
struct node
{
int a;
int b;
bool operator < (const node &t) const{
return b<t.b;
}
};
int main()
{
priority_queue<node> q;
node pp;
for(int i=0;i<3;i++)
{
scanf("%d %d",&pp.a,&pp.b);
q.push(pp);
}
while(!q.empty())
{
pp=q.top();
q.pop();
cout << pp.a << " " << pp.b << endl;
}
return 0;
}