priority queue ordered by second element 1

priority queue ordered by second element

#include 
using namespace std;

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

int main() {
    //Max heap custom data type
    priority_queue, 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
    */
}

Here is what the above code is Doing:
1. We create a priority queue p of type Max.
2. We push three pairs into the priority queue.
3. We pop the elements from the priority queue one by one till it becomes empty.

The output of the above code is:
b => 3
a => 1
c => 1

As you can see, the elements are popped in the descending order of their second value.

Similar Posts