Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateSTL Containers ProgramsExample 9 of 10
priority-queue.cpp
1#include <iostream>
2#include <queue>
3#include <vector>
4using namespace std;
5
6int main() {
7 // Max heap (default - largest element at top)
8 priority_queue<int> pq;
9
10 pq.push(30);
11 pq.push(10);
12 pq.push(50);
13 pq.push(20);
14 pq.push(40);
15
16 cout << "Priority Queue (Max Heap):" << endl;
17 cout << "Top element (maximum): " << pq.top() << endl;
18
19 cout << "\nElements in descending order:" << endl;
20 while (!pq.empty()) {
21 cout << pq.top() << " ";
22 pq.pop();
23 }
24 cout << endl;
25
26 // Min heap
27 priority_queue<int, vector<int>, greater<int>> minHeap;
28
29 minHeap.push(30);
30 minHeap.push(10);
31 minHeap.push(50);
32 minHeap.push(20);
33 minHeap.push(40);
34
35 cout << "\nPriority Queue (Min Heap):" << endl;
36 cout << "Top element (minimum): " << minHeap.top() << endl;
37
38 cout << "\nElements in ascending order:" << endl;
39 while (!minHeap.empty()) {
40 cout << minHeap.top() << " ";
41 minHeap.pop();
42 }
43 cout << endl;
44
45 // Custom comparator
46 auto cmp = [](int a, int b) { return a > b; };
47 priority_queue<int, vector<int>, decltype(cmp)> customPQ(cmp);
48
49 customPQ.push(5);
50 customPQ.push(2);
51 customPQ.push(8);
52
53 cout << "\nCustom Priority Queue:" << endl;
54 while (!customPQ.empty()) {
55 cout << customPQ.top() << " ";
56 customPQ.pop();
57 }
58 cout << endl;
59
60 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. 1

    Push 30, 10, 50, 20, 40 into the default queue; top = 50.

  2. 2

    Pop all: 50 40 30 20 10.

  3. 3

    Build a min-heap with greater<int>; top = 10.

  4. 4

    Pop all: 10 20 30 40 50.

  5. 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:

Binary heap data structure
Root contains max (or min) element
Maintains heap property
Efficient priority access

Key Features:

O(1) access to top element
O(log n) insert/delete
Max heap (default) or min heap
Priority-based ordering

Max Heap (Default)

Declaration:

priority_queue<int> pq;

Operations:

pq.push(30); // Insert

pq.top(); // Access maximum

pq.pop(); // Remove maximum

What happens here:

Largest element always at top
Maintains max heap property
O(log n) insert/delete
O(1) top access

Min Heap

Declaration:

priority_queue<int, vector<int>, greater<int>> minHeap;

What happens here:

Template: priority_queue<Type, Container, Comparator>
greater<int>: makes it min heap
Smallest element at top
Useful for finding minimum

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:

Custom comparison function
Defines priority order
Flexible ordering
Can use any comparison logic

When to Use Priority Queue

Good fits:

Dijkstra's algorithm
Heap sort
Task scheduling by priority
Finding k largest/smallest
Event simulation
Merge k sorted lists

Example Scenarios:

Shortest path algorithms
Top K elements
Priority-based scheduling
Median finding
Huffman coding

Important Considerations

Heap Property:

Max heap: parent >= children
Min heap: parent <= children
Maintained automatically
Top element always max/min

Performance:

Top access: O(1)
Insert: O(log n)
Delete: O(log n)
Efficient for priority operations

No Random Access:

Only top element accessible
Must pop to access other elements
Use other containers if random access needed

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.