C++ STL priority_queue


 

C++ STL priority_queue

标签: c++vector
 17801人阅读 评论(3) 收藏 举报
 分类:

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

[cpp] view plain copy
  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<>,对于基本类型可以用这个仿函数声明小顶堆
例子:

[cpp] view plain copy
  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< 或者自己写仿函数先看看例子:

[cpp] view plain copy
  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的自定义比较函数也可以写成这种形式

[cpp] view plain copy
  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. }  

原文地址:https://www.cnblogs.com/nyist-xsk/p/7264888.html