C++ priority_queue的使用 & Java PriorityQueue

刚刚那道BST的题目,也用到了priority_queue,那是那个没有定义比较函数。

那么下面这个,就要定义比较函数。

它的模板声明带有三个参数,priority_queue<Type, Container, Functional>

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


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

或者重载比较符号,也可以:

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

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

就不需要在类型里面定义了。

或者这样定义也是能达到效果的:

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

    friend operator<( Node a, Node b ){
    if( a.x== b.x ) return a.y> b.y;
    return a.x> b.x;

    }
};

http://blog.csdn.net/sraing/article/details/6256302

Java

PriorityQueue<Cell> queue = new PriorityQueue<>(1, new Comparator<Cell>(){
            public int compare(Cell a, Cell b) {
                return a.height - b.height;
            }
        });
原文地址:https://www.cnblogs.com/charlesblc/p/6446518.html