Saturday, October 25, 2025
HomeData Modelling & AIPriority queue of pairs in C++ (Ordered by first)

Priority queue of pairs in C++ (Ordered by first)

In C++, priority_queue implements heap. Below are some examples of creating priority queue of pair type.

Max Priority queue (Or Max heap) ordered by first element




// C++ program to create a priority queue of pairs.
// By default a max heap is created ordered
// by first element of pair.
#include <bits/stdc++.h>
  
using namespace std;
  
// Driver program to test methods of graph class
int main()
{
    // By default a max heap is created ordered
    // by first element of pair.
    priority_queue<pair<int, int> > pq;
  
    pq.push(make_pair(10, 200));
    pq.push(make_pair(20, 100));
    pq.push(make_pair(15, 400));
  
    pair<int, int> top = pq.top();
    cout << top.first << " " << top.second;
    return 0;
}


Output :

20 100


Min Priority queue (Or Min heap) ordered by first element




// C++ program to create a priority queue of pairs.
// We can create a min heap by passing adding two 
// parameters, vector and greater().
#include <bits/stdc++.h>
  
using namespace std;
  
typedef pair<int, int> pi;
  
// Driver program to test methods of graph class
int main()
{
    // By default a min heap is created ordered
    // by first element of pair.
    priority_queue<pi, vector<pi>, greater<pi> > pq;
  
    pq.push(make_pair(10, 200));
    pq.push(make_pair(20, 100));
    pq.push(make_pair(15, 400));
  
    pair<int, int> top = pq.top();
    cout << top.first << " " << top.second;
    return 0;
}


Output :

10 200
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS