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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Priority queue of pairs in C++ with ordering by first and second element
- Implementation of Non-Preemptive Shortest Job First using Priority Queue
- Why is Binary Heap Preferred over BST for Priority Queue?
- Applications of Priority Queue
- How to implement stack using priority queue or heap?
- STL Priority Queue for Structure or Class
- Does STL priority queue allow duplicate values?
- Priority Queue in Python
- Double ended priority queue
- Priority Queue of Vectors in C++ STL with Examples
- Find the K closest points to origin using Priority Queue
- Priority Queue using Binary Heap
- Priority Queue in C++ Standard Template Library (STL)
- Find k ordered pairs in array with minimum difference d
- queue::empty() and queue::size() in C++ STL
- queue::push() and queue::pop() in C++ STL
- queue::front() and queue::back() in C++ STL
- Ordered Prime Signature
- Queue of Pairs in C++ STL with Examples
- Scheduling priority tasks in limited time and minimizing loss
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : addiegupta

