priority_queue用法

来源:互联网 发布:mac上能玩的热门网游 编辑:程序博客网 时间:2024/04/30 11:13

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

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

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

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

  1. #include  
  2. #include  
  3. #include  
  4.  
  5. using namespace std; 
  6.  
  7. class priority_queue 
  8. {  
  9.     private
  10.         vector<</span>intdata; 
  11.          
  12.     public
  13.         void push( int ){  
  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( ); 
  32.     test.push( ); 
  33.     test.push( ); 
  34.     test.push( ); 
  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 为元素比较方式。
Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.
STL里面默认用的是 vector. 比较方式默认用 operator< ,所以如果你把后面俩个
参数缺省的话,优先队列就是大顶堆,队头元素最大。
(1)使用默认参数

  1. #include  
  2. #include  
  3. using namespace std; 
  4.  
  5. int main(){ 
  6.     priority_queue<</span>intq; 
  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等,或者重载<,这样就不需要用三个参数,或者自定义比较函数)

priority_queue, greater>;

 

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

priority_queue

 

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

priority_queue,cmp>;

 

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

如果要以结构体为优先队列元素的话,则可以这么写

 

#include<iostream>

#include<queue>



using namespace std;



struct node{

  int idx;

  int key;

  node(int a=0, intb=0):idx(a), key(b){}

};


struct cmp{

  bool operator()(node a,node b){

    returna.key > b.key;

  }

};

int main(){

  

 priority_queue<node,vector<node>, cmp>q;

  

  int i;

 for(i=0;i<10;++i){

   q.push(node(i, i));

  }


 while(!q.empty()){

   cout<<q.top().key<<endl;

   q.pop();

  }

  return 0;

}

a>b和a<b的结果到底是什么?最后,我想到了一个场景来记忆这里的比较函数的意义:a,b是该数据结构中前后两个元素,如果返回true,这两个元素就需要交换位置,反之则不需要。

0 0
原创粉丝点击