c++中小项堆声明和使用

c++默认是大顶堆,小顶堆有两种声明方法:

1、对于基本类型直接用

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

如果基本类型是pair:

在代码第一行写:

typedef pair<int, int> P;

 priority_queue<P, vector<P>, greater<P>>pq;

注:greater<int> 是个好东西,把一个vector v从大到小排序用的就是sort(v.begin(), v.end(), greater<int>());

2、对于自定义类型,则必须自己重载 operator< 或者自己写仿函数

#include <iostream>

#include <queue>

using namespace std;

struct Node{
    int x, y;
    Node( int a= 0, int b= 0 ):
        x(a), y(b) {}
};

struct cmp{
    bool operator() ( Node a, Node b ){
        if( a.x== b.x ) return a.y> b.y;
       
        return a.x> b.x; }
};

int main(){
    priority_queue<Node, vector<Node>, cmp> q;
   
    for( int i= 0; i< 10; ++i )
    q.push( Node( rand(), rand() ) );
   
    while( !q.empty() ){
        cout << q.top().x << ' ' << q.top().y << endl;
        q.pop();
    }
   
    getchar();
    return 0;
}

posted on 2016-12-15 19:34  Joker_88  阅读(594)  评论(0编辑  收藏  举报

导航