c++ 优先队列 priority_queue 用法简介

来源:互联网 发布:人工智能需要的专业 编辑:程序博客网 时间:2024/06/16 09:34
#include <iostream>#include <queue>using namespace std;struct Node{    int x, y;    Node( int a= 0, int b= 0 ):        x(a), y(b) {}};bool operator<( Node a, Node b ){   // 注意这里的顺序和sort()里面的谓词函数不一样!// bool为真的 优先级小      if( a.x== b.x ) return a.y> b.y;    return a.x> b.x; }      //自定义重载小于操作符 int main(){    priority_queue<int> q;  //省略后面两个参数,priority_queue<Type, Container, Functional>/***************************************Type 为数据类型, Container 为保存数据的容器,Functional 为元素比较方式Container 必须是用数组实现的容器,比如 vector, deque 但不能用 list.STL里面默认用的是 vector. 比较方式默认用 operator< , 所以如果你把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大*****************************************/     for( int i= 0; i< 10; ++i ) q.push( rand()%100 );    while( !q.empty() ){        cout << q.top() << endl;        q.pop();    }    /****************************************    如果要用到小顶堆,则一般要把模板的三个参数都带进去    STL里面定义了一个函数对象 greater<>,对于基本类型可以用这个仿函数声明小顶堆    下面是例子:        ****************************************/    cout<<"小堆: "<<endl;     priority_queue<int, vector<int>, greater<int> > q1;    for( int i= 0; i< 10; ++i ) q1.push( rand()%100 );    while( !q1.empty() ){        cout << q1.top() << endl;        q1.pop();    }   /********************************************   对于自定义类型,则必须自己重载 operator<    自定义类型重载 operator< 后,声明对象时就可以只带一个模板参数。   看下面的例子    *******************************************/       cout<<"自定义: "<<endl;        priority_queue<Node> q2;        for( int i= 0; i< 10; ++i )    q2.push( Node( rand()%10, rand()%10 ) );        while( !q2.empty() ){        cout << q2.top().x << ' ' << q2.top().y << endl;        q2.pop();    }//注意上面不能这样来定义:priority_queue<Node, vector<Node>, greater<Node> >;//这样定义是错误的!!!!//原因是:greater<node>没有定义//必须定义如下函数对象,才能这样定义:// priority_queue<Node, vector<Node>, cmp >;struct cmp{    bool operator() ( Node a, Node b ){        if( a.x== b.x ) return a.y> b.y;                return a.x> b.x; }};     return 0;}

原创粉丝点击