How to Use priority_queue in C++: Syntax and Examples
In C++, use
std::priority_queue to store elements in a way that the largest element is always accessible at the top. It works like a max-heap by default, and you can push elements with push(), access the top with top(), and remove it with pop().Syntax
The std::priority_queue is a container adapter that provides a priority queue interface. It is declared as:
std::priority_queue<Type, Container, Compare> pq;
Where:
Typeis the data type stored.Containeris the underlying container type (default isstd::vector<Type>).Compareis the comparison function object that defines priority (default isstd::less<Type>for max-heap).
cpp
std::priority_queue<int> pq; // max-heap of integers by default
Example
This example shows how to create a priority queue, add elements, access the top element, and remove elements in order of priority.
cpp
#include <iostream> #include <queue> int main() { std::priority_queue<int> pq; pq.push(10); pq.push(30); pq.push(20); pq.push(5); std::cout << "Elements in priority order:" << std::endl; while (!pq.empty()) { std::cout << pq.top() << " "; pq.pop(); } std::cout << std::endl; return 0; }
Output
Elements in priority order:
30 20 10 5
Common Pitfalls
Common mistakes when using priority_queue include:
- Trying to iterate over the queue directly (it does not support iterators).
- Assuming it sorts all elements (it only guarantees the top is the highest priority).
- Not specifying a custom comparator correctly for min-heap behavior.
To create a min-heap, you must use std::greater<Type> as the comparator and specify the container:
cpp
#include <queue> #include <vector> #include <functional> // Correct way to create min-heap: std::priority_queue<int, std::vector<int>, std::greater<int>> min_pq; // Wrong: Trying to iterate directly over pq (no iterators) // for (auto x : pq) { /* error */ }
Quick Reference
| Operation | Description | Example |
|---|---|---|
| push | Add element to the queue | pq.push(5); |
| top | Access highest priority element | int x = pq.top(); |
| pop | Remove highest priority element | pq.pop(); |
| empty | Check if queue is empty | if (pq.empty()) {...} |
| size | Get number of elements | int n = pq.size(); |
Key Takeaways
Use std::priority_queue to always access the largest element quickly by default.
Push elements with push(), access the top with top(), and remove it with pop().
To create a min-heap, specify std::greater as the comparator and vector as the container.
You cannot iterate directly over a priority_queue; only access top element.
Remember priority_queue only guarantees the top element priority, not full sorting.