метод 1, с использованием функтора ,
#include <unordered_map>
#include <vector>
#include <iostream>
#include <queue>
using namespace std;
typedef pair<char, int> PAIR;
int main(int argc, char *argv[]) {
unordered_map<char, int> dict = {{'a', 12}, {'b', 9}, {'c', 7}, {'d', 10},};
struct cmp {
bool operator()(const PAIR &a, const PAIR &b) {
return a.second < b.second;
};
};
priority_queue<PAIR, vector<PAIR>, cmp> pq(dict.begin(), dict.end());
while (!pq.empty()) {
PAIR top = pq.top();
cout << top.first << " - " << top.second << endl;
pq.pop();
}
}
метод 2, с использованием функции и decltype()
it
auto cmp = [](const PAIR &a, const PAIR &b) {
return a.second < b.second;
};
priority_queue<PAIR, vector<PAIR>, decltype(cmp)> pq(
dict.begin(), dict.end(), cmp);
priority_queue в приведенном выше примере отсортировано по значению,
a - 12
d - 10
b - 9
c - 7