priority_queue本质是一个堆。
- 头文件是#include
- 关于模板参数
模板申明带3个参数:priority_queue<Type, Container, Functional>
Type 为数据类型
Container为保存数据的容器:必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector。
Functional 为元素比较方式:比较方式默认用operator<,所以如果把后面2个参数缺省的话,优先队列就是大顶堆(降序),队头元素最大。特别注意pair的比较函数。
//返回降序输入
#include <iostream>
#include <queue>
using namespace std;
int main(){
priority_queue<int> q;
for( int i= 0; i< 10; ++i ) q.push(i);
while( !q.empty() ){
cout<<q.top()<<endl;
q.pop();
}
return 0;
}
关于优先级队列priority_queue之比较函数
常用为
greater<> //升序
priority_queue<int, vector<int>, greater<int> > q;
可以以自定义比较函数
但必须重载operator<或者重写仿函数
返回true时,说明左边形参的优先级低于右边形参
struct cmp{
bool operator() ( int a , int b ){
return a< b; //与greater是等价的
}
};
priority_queue<int,vector<int>,cmp > p;
复杂一点的例子
小顶堆,先按x升序,x相等时,再按y升序
#include <iostream>
#include <queue>
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 ){//默认是less函数
//返回true时,a的优先级低于b的优先级(a排在b的后面)
if( a.x== b.x ) return a.y> b.y;
return a.x> b.x; }
};
int main(){
priority_queue<Node, vector<Node>, cmp> q;
for( int i= 0; i< 10; ++i )
q.push( Node( rand(), rand() ) );
while( !q.empty() ){
cout << q.top().x << ' ' << q.top().y << endl;
q.pop();
}
return 0;
}
priority_queue的操作
本文参考https://www.cnblogs.com/Deribs4/p/5657746.html
更多资料在http://c.biancheng.net/view/480.html