用STL实现优先队列

#include<iostream>
#include<queue>
using namespace std;
struct node{
       int a;
       int b;
       };
struct cmp{                       //reset operator for node
      bool operator ()(const node &c,const node &d){
           return (c.a<d.a);                  //from high to low
           }
           };
int main(){
    int c[5]={3,1,12,6,5};
    node b[5];
     b[0].a=2;
     b[1].a=5;
     b[3].a=2;
     b[2].a=7;
     b[4].a=1;
     b[0].b=4;
     b[1].b=3;
     b[3].b=10;
     b[2].b=5;
     b[4].b=3;
    priority_queue<int> q;             //from high to low  
    for(int i=0;i<5;i++){
           q.push(c[i]);
           }
    for(int j=0;j<5;j++){
           cout<<q.top()<<" ";
           q.pop();
            }
    cout<<endl;
   
   
    priority_queue<int,vector<int>,greater<int> >q0;     //from low to high
    for(int i=0;i<5;i++){
           q0.push(c[i]);
           }
    for(int j=0;j<5;j++){
           cout<<q0.top()<<" ";
           q0.pop();
            }
    cout<<endl;
   
   
     for(int k=0;k<5;k++){
            //   b[k].a=k+1;
             //  b[k].b=(k+3)%6;
               cout<<b[k].a<<" "<<b[k].b<<endl;
               }
     priority_queue<node,vector<node>,cmp > q1;           //cmp is reset for node class
      for(int i=0;i<5;i++){
           q1.push(b[i]);
           }
    for(int j=0;j<5;j++){
           node temp;
        //   temp=q
           cout<<(q1.top()).a<<" ";
           q1.pop();
            }
    cout<<endl;
               
    system("pause");
    return 0;
}
   

STL中的queue:

        默认的排序为由大到小;可用greater改为由小到大。

        当queue中的元素为struct时,其运算符需要重载。

        top()函数只是得到队首元素,不会将其从队列中取出。

posted on 2012-07-01 11:28  yumao  阅读(275)  评论(0编辑  收藏  举报

导航