What is priority_queue in C++: Explanation and Example
priority_queue is a container adapter that stores elements in a way that the largest element is always accessible at the top. It works like a max-heap by default, allowing fast retrieval of the highest priority element.How It Works
A priority_queue in C++ is like a special kind of waiting line where the person with the highest priority always gets served first, no matter when they arrived. Instead of serving people in the order they come, it always picks the one with the biggest value or highest priority.
Under the hood, it uses a structure called a heap, which is like a tree where each parent node is bigger than its children. This makes it very fast to find and remove the largest element. When you add a new element, the queue rearranges itself to keep the biggest element on top.
Example
This example shows how to create a priority_queue, add numbers, and get the largest number each time.
#include <iostream> #include <queue> int main() { std::priority_queue<int> pq; pq.push(10); pq.push(30); pq.push(20); pq.push(5); while (!pq.empty()) { std::cout << pq.top() << " "; pq.pop(); } return 0; }
When to Use
Use a priority_queue when you need quick access to the largest (or highest priority) item, like in task scheduling, event simulation, or algorithms such as Dijkstra's shortest path. It helps when order matters more than arrival time, and you want to always process the most important item first.
Key Points
- priority_queue stores elements so the largest is always on top.
- It uses a max-heap by default for fast access.
- You can customize it to behave like a min-heap if needed.
- Commonly used in algorithms needing priority-based processing.