c++中小项堆声明和使用【转】

时间:2023-03-10 06:39:27
c++中小项堆声明和使用【转】

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

1、对于基本类型直接用

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

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;
}