优先级队列

131 阅读1分钟
#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) {//默认是less函数
        //返回true时,a的优先级低于b的优先级(a排在b的后面)
        if (a.x == b.x) return a.y > b.y;
        return a.x > b.x;
    }
};*/

int main() {
    int z = 1000;
    auto cmp = [z](Node a, Node b) {
        if (a.x == b.x) return a.y > b.y;
        return a.x > b.x;
    };
    priority_queue<Node, vector<Node>, decltype(cmp)> q(cmp);
    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();
    }
    return 0;
}