翻了很多博客的总结
1、头文件
#include<queue>
2、定义
- priority_queue<int> p;
3、优先输出大数据
priority_queue<Type, Container, Functional>
Type为数据类型, Container为保存数据的容器,Functional为元素比较方式。
如果不写后两个参数,那么容器默认用的是vector,比较方式默认用operator<,也就是优先队列是大顶堆,队头元素最大。
例如:
- #include<iostream>
- #include<queue>
- using namespace std;
- int main(){
- priority_queue<int> p;
- p.push(1);
- p.push(2);
- p.push(8);
- p.push(5);
- p.push(43);
- for(int i=0;i<5;i++){
- cout<<p.top()<<endl;
- p.pop();
- }
- return 0;
- }
输出:
4、优先输出小数据
方法一:
- priority_queue<int, vector<int>, greater<int> > p;
例如:
- #include<iostream>
- #include<queue>
- using namespace std;
- int main(){
- priority_queue<int, vector<int>, greater<int> >p;
- p.push(1);
- p.push(2);
- p.push(8);
- p.push(5);
- p.push(43);
- for(int i=0;i<5;i++){
- cout<<p.top()<<endl;
- p.pop();
- }
- return 0;
- }
输出:
方法二:自定义优先级,重载默认的 < 符号
例子:
- #include<iostream>
- #include<queue>
- #include<cstdlib>
- using namespace std;
- struct Node{
- int x,y;
- Node(int a=0, int b=0):
- x(a), y(b) {}
- };
- struct cmp{
- bool operator()(Node a, Node b){
- if(a.x == b.x) return a.y>b.y;
- return a.x>b.x;
- }
- };
- int main(){
- priority_queue<Node, vector<Node>, cmp>p;
- for(int i=0; i<10; ++i)
- p.push(Node(rand(), rand()));
- while(!p.empty()){
- cout<<p.top().x<<' '<<p.top().y<<endl;
- p.pop();
- }//while
- //getchar();
- return 0;
- }
输出:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
struct package
{ int id;
string data;
};
bool operator<(package a, package b)
{ return a.id < b.id;} //自定义排序规则
int main()
{ priority_queue<package> tmp;
tmp.push({3,"a"});
tmp.push({2,"b"});
int size = tmp.size();
while(size--)
{ cout << tmp.top().id << " " << tmp.top().data <<endl;
tmp.pop();
}
}
以结构体Time为例:
- struct Time{
- int start, end;
- };
- priority_queue<Time> pq;
- bool operator <(const Time& a,const Time& b){
- return a.start > b.start;
- } //这里以大于重载小于是因为默认情况下,优先队列是以大的作为队首,这样一反,就可以再默认情况下使得小的作为队首
二.直接在结构体中重载小于运算符:
- struct Time{
- int start, end;
- bool operator < (const Time& t)const{
- return start > t.start;
- }
- };
实质上来说是一样的。。。。
另外要注意的是:参数列表中的const不能省略,否则报错~~
默认的优先队列是个极大堆,如果要改变优先队列中元素的优先级,有下面这些方法
- struct cmp1
- {
- bool operator ()(int &a,int &b)
- {
- return a>b;//最小值优先
- }
- };
- struct cmp2
- {
- bool operator ()(int &a,int &b)
- {
- return a<b;//最大值优先
- }
- };
- struct node1
- {
- int u;
- bool operator < (const node1 &a) const
- {
- return u>a.u;//最小值优先
- }
- };
- struct node2
- {
- int u;
- bool operator < (const node2 &a) const
- {
- return u<a.u;//最大值优先
- }
- };
- priority_queue<int>q1;//采用默认优先级构造队列
- priority_queue<int,vector<int>,cmp1>q2;//最小值优先
- priority_queue<int,vector<int>,cmp2>q3;//最大值优先
- priority_queue<int,vector<int>,greater<int> >q4;//注意“>>”会被认为错误,
- //这是右移运算符,所以这里用空格号隔开,最小值优先
- priority_queue<int,vector<int>,less<int> >q5;//最大值优先
- priority_queue<node1>q6; //自定义优先级
- priority_queue<node2>q7;