C++ 自定义结构体的Priority Queue
比较函数return true 意味着排序需要交换。
#include <iostream> #include <queue> #include <vector> #include <algorithm> using namespace std; struct Item { int val = 0; int idx = 0; }; /** * want ascending order, if ties, prefer less idx * return true if we want swap happen * */ class Compare { public: bool operator() (const Item &lhs, const Item &rhs) { if (lhs.val == rhs.val) { return lhs.idx > rhs.idx; } return lhs.val < rhs.val; } }; int main() { Item item1; item1.val = 1; item1.idx = 1; Item item2; item2.val = 2; item2.idx = 2; vector<Item> v = {item1, item2}; priority_queue<Item, vector<Item>, Compare> myPQ(v.begin(),v.end()); cout << myPQ.top().idx << endl; std::sort(v.begin(),v.end(), Compare()); cout << v[0].val << endl; return 0; }