priority_queue用法

在优先队列中,优先级高的元素先出队列。
 

先写一个用 STL 里面堆算法实现的与真正的STL里面的 priority_queue 用法相
似的 priority_queue, 以加深对 priority_queue 的理解

push_heap():将容器中的最后一个元素加入堆中

pop_head():将堆中最大的(或者自定义比较函数,默认为<)元素推到容器首

 
 
  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <vector>  
  4.  
  5. using namespace std;  
  6.  
  7. class priority_queue  
  8. {  
  9.     private:  
  10.         vector<int> data;  
  11.           
  12.     public:  
  13.         void push( int t ){   
  14.             data.push_back(t);   
  15.             push_heap( data.begin(), data.end());   
  16.         }  
  17.           
  18.         void pop(){  
  19.             pop_heap( data.begin(), data.end() );  
  20.             data.pop_back();  
  21.         }  
  22.           
  23.         int top()    { return data.front(); }  
  24.         int size()   { return data.size();  }  
  25.         bool empty() { return data.empty(); }  
  26. };  
  27.  
  28. int main()  
  29. {  
  30.     priority_queue  test;  
  31.     test.push( 3 );  
  32.     test.push( 5 );  
  33.     test.push( 2 );  
  34.     test.push( 4 );  
  35.       
  36.     while( !test.empty() ){  
  37.         cout << test.top() << endl;  
  38.         test.pop(); }  
  39.           
  40.     return 0;  
  41. }  
 运行结果:

 

STL里面的 priority_queue 写法与此相似,只是增加了模板及相关的迭代器什么的。


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

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

(2)自定义比较函数(可以使用STL里的函数greater<int>等,或者重载<,这样就不需要用三个参数,或者自定义比较函数)

priority_queue<int, vector<int>, greater<int>>;

 

bool operator<  (int a,int b){return a < b;}

priority_queue<int>

 

bool cmp(int a,int b) { return a < b;}

priority_queue<int,vector<int>,cmp>;

 

本文出自 “牛哥的博客” 博客,请务必保留此出处http://nxlhero.blog.51cto.com/962631/699349

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值