Priority Queue in C++
C++ priority_queue explained: a max-heap by default, a min-heap with greater<int>, and a lambda comparator, with why the comparator direction feels backwards.
1#include <iostream>2#include <queue>3#include <vector>4using namespace std;56int main() {7 // Max heap (default - largest element at top)8 priority_queue<int> pq;910 pq.push(30);11 pq.push(10);12 pq.push(50);13 pq.push(20);14 pq.push(40);1516 cout << "Priority Queue (Max Heap):" << endl;17 cout << "Top element (maximum): " << pq.top() << endl;1819 cout << "\nElements in descending order:" << endl;20 while (!pq.empty()) {21 cout << pq.top() << " ";22 pq.pop();23 }24 cout << endl;2526 // Min heap27 priority_queue<int, vector<int>, greater<int>> minHeap;2829 minHeap.push(30);30 minHeap.push(10);31 minHeap.push(50);32 minHeap.push(20);33 minHeap.push(40);3435 cout << "\nPriority Queue (Min Heap):" << endl;36 cout << "Top element (minimum): " << minHeap.top() << endl;3738 cout << "\nElements in ascending order:" << endl;39 while (!minHeap.empty()) {40 cout << minHeap.top() << " ";41 minHeap.pop();42 }43 cout << endl;4445 // Custom comparator46 auto cmp = [](int a, int b) { return a > b; };47 priority_queue<int, vector<int>, decltype(cmp)> customPQ(cmp);4849 customPQ.push(5);50 customPQ.push(2);51 customPQ.push(8);5253 cout << "\nCustom Priority Queue:" << endl;54 while (!customPQ.empty()) {55 cout << customPQ.top() << " ";56 customPQ.pop();57 }58 cout << endl;5960 return 0;61}
Sample Output
Top element (maximum): 50
Default max-heap.
2 5 8
The lambda a > b is a min-heap.
In this one
- How a heap keeps the top element ready
- How to build a max-heap and a min-heap
- Why greater gives a min-heap
- How to pass a lambda comparator
How it works
- 1
Push 30, 10, 50, 20, 40 into the default queue; top = 50.
- 2
Pop all: 50 40 30 20 10.
- 3
Build a min-heap with greater<int>; top = 10.
- 4
Pop all: 10 20 30 40 50.
- 5
Build a lambda min-heap with 5, 2, 8 and pop: 2 5 8.
Edge cases
Equal priorities
Push 5 twice.
Both come out, one after the other. The order among equal items is not guaranteed to follow insertion order.
top() on an empty queue
Call pq.top() after the loop.
Undefined behavior. Check empty() first.
What's going on
A priority_queue always hands you the highest-priority item next, no matter when it was added. By default, "highest priority" means the largest value.
It is built on a heap, a tree stored inside a vector where every parent is at least as large as its children. That keeps the largest element at the top. push and pop cost O(log n), and top() is O(1).
The first queue gets 30, 10, 50, 20, 40. top() is 50. Popping until empty prints 50 40 30 20 10, so a priority queue is also a way to sort.
The min-heap uses the full template form priority_queue<int, vector<int>, greater<int>>. The three parts are the element type, the container underneath, and the comparison. With greater<int> the smallest value rises to the top, so it prints 10 20 30 40 50.
The comparator rule is backwards from what most people expect. The comparator answers "should a come after b?", and the element that compares as greatest ends up on top. The default less<int> therefore gives a max-heap, and greater<int> gives a min-heap.
The custom example passes a lambda [](int a, int b) { return a > b; }. That is the same rule as greater, so it is another min-heap and prints 2 5 8. decltype(cmp) gives the lambda's type for the template, and customPQ(cmp) passes the lambda object itself. With a lambda you can order by anything, such as a task's deadline or the second value of a pair.
You cannot iterate over a priority queue or look at anything except the top.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <queue> is there because it provides priority_queue container class. <vector> is there because it provides vector for priority_queue implementation. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Priority Queue
Heap Concept:
Key Features:
Max Heap (Default)
Declaration:
priority_queue<int> pq;
Operations:
pq.push(30); // Insert
pq.top(); // Access maximum
pq.pop(); // Remove maximum
What happens here:
Min Heap
Declaration:
priority_queue<int, vector<int>, greater<int>> minHeap;
What happens here:
Custom Comparator
Lambda Comparator:
auto cmp = [](int a, int b) { return a > b; };
priority_queue<int, vector<int>, decltype(cmp)> customPQ(cmp);
What happens here:
When to Use Priority Queue
Good fits:
Example Scenarios:
Important Considerations
Heap Property:
Performance:
No Random Access:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which declaration gives the smallest element at top()?
Pick an answer to check it.
Question 2
What do push and pop cost?
Pick an answer to check it.
Questions people ask
How do I get a max-heap of pairs ordered by the second value?
Write a comparator such as [](auto& a, auto& b){ return a.second < b.second; }.
Can I change an item's priority?
Not directly. A common trick is to push the new version and skip stale ones when they reach the top.
Where are priority queues used?
Dijkstra's shortest path, task scheduling, and finding the k largest items.