1、使用常规方法实现
使用结构体实现自定义排序函数
2、使用lambda表达式实现
使用lambda表达式实现自定义排序函数
3、具体实现如下:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
using Pair = pair<int, int>;
class Test {
public:
void FirstFun(const vector<Pair>& data) {
priority_queue<Pair, vector<Pair>, Test::cmp> priorityQueue(data.begin(), data.end());
cout << "First fun:" << endl;
while (!priorityQueue.empty()) {
const auto& topItem = priorityQueue.top(); // 使用常量引用
cout << "(" << topItem.first << "," << topItem.second << ")" << endl;
priorityQueue.pop();
}
}
void SecondFun(const vector<Pair>& data) {
auto cmp1 = [](const Pair& lhs, const Pair& rhs) {
return lhs.second > rhs.second;
};
priority_queue<Pair, vector<Pair>, decltype(cmp1)> priorityQueue(data.begin(), data.end(), cmp1);
cout << "Second fun:" << endl;
while (!priorityQueue.empty()) {
const auto& topItem = priorityQueue.top(); // 使用常量引用
cout << "(" << topItem.first << "," << topItem.second << ")" << endl;
priorityQueue.pop();
}
}
private:
struct cmp {
bool operator()(const Pair& litem, const Pair& ritem) {
return litem.second > ritem.second;
}
};
};
int main() {
Test test;
vector<Pair> vec = {{6, 5}, {5, 2}, {3, 7}};
test.FirstFun(vec);
test.SecondFun(vec);
return 0;
}
4、运行结果: