Answers for "priority queue ordered by second element"

C++
1

priority queue ordered by second element

#include <bits/stdc++.h>
using namespace std;

typedef pair<string, int> Max;
struct Compare {
    bool operator()(Max a, Max b) {
        return a.second < b.second;
    }
};

int main() {
    //Max heap custom data type
    priority_queue<Max, vector<Max>, Compare> p;
    p.push(make_pair("a", 1));
    p.push(make_pair("c", 1));
    p.push(make_pair("b", 3));

    while (!p.empty()) {
        Max top = p.top();
        cout << top.first << " => " << top.second << "\n";
        p.pop();
    }
    /*
    * OUTPUT:
    * b = 3
    * a = 1
    * c = 1
    */
}
Posted by: Guest on August-21-2021

Browse Popular Code Answers by Language