C++ 优先队列priority_queue用法【转载】

priority_queue 对于基本类型的使用方法相对简单。他的模板声明带有三个参数,priority_queue<Type, Container, Functional>
Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式。
Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.
STL里面容器默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数 缺省的话,优先队列就是大顶堆,队头元素最大。
看例子

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 int main(){
 5     priority_queue<int,vector<int>,less<int> >q;//使用priority_queue<int> q1;一样
 6     for(int i=0;i<10;i++) 
 7         q1.push(i);
 8     while(!q1.empty()){
 9         cout<<q1.top()<< endl;
10         q1.pop();
11     }
12     return 0;
13 }

如果要用到小顶堆,则一般要把模板的三个参数都带进去。
STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆
例子:

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 int main(){
 5     priority_queue<int,vector<int>,greater<int> >q;
 6     for(int i=0;i<10;i++) 
 7         q.push(i);
 8     while(!q.empty()){
 9         cout<<q.top()<< endl;
10         q.pop();
11     }
12     return 0;
13 }

对于自定义类型,则必须自己重载 operator< 或者自己写仿函数先看看例子:

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 struct Node{
 5     int x, y;
 6 }node;
 7  bool operator<( Node a, Node b){
 8     if(a.x==b.x) return a.y>b.y;
 9     return a.x>b.x;
10 }
11  int main(){
12     priority_queue<Node>q;
13     for(int i=0;i<10;i++){
14         node.x=i;
15         node.y=10-i/2;
16         q.push(node);
17     }    
18     while(!q.empty()){
19         cout<<q.top().x <<' '<<q.top().y<<endl;
20         q.pop();
21     }
22     return 0;
23 }

自定义类型重载 operator< 后,声明对象时就可以只带一个模板参数。
此时不能像基本类型这样声明priority_queue<Node, vector<Node>, greater<Node> >;
原因是 greater<Node> 没有定义,如果想用这种方法定义
则可以按如下方式

例子:(个人喜欢这种方法,因为set的自定义比较函数也可以写成这种形式)

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 struct Node{
 5     int x, y;
 6 }node;
 7 struct cmp{
 8     bool operator()(Node a,Node b){
 9         if(a.x==b.x) return a.y>b.y;
10         return a.x>b.x;}
11 };
12 
13  int main(){
14     priority_queue<Node,vector<Node>,cmp>q;
15     for(int i=0;i<10;i++){
16         node.x=i;
17         node.y=10-i/2;
18         q.push(node);    
19     }    
20     while(!q.empty()){
21         cout<<q.top().x<<' '<<q.top().y<<endl;
22         q.pop();
23     }
24     return 0;
25 }

 转载自Sup_Heaven

posted on 2016-04-08 13:08  北方暴雪  阅读(506)  评论(0编辑  收藏  举报