Core Module
12 min forge
C++ STL Priority Queue
Mastering heap-based containers for efficient maximum/minimum element retrieval.
C++ STL Priority Queue
π What is it
std::priority_queue is a container adaptor that provides constant time lookup of the largest (by default) element, at the expense of logarithmic insertion and extraction.
β‘ When to use
Essential for algorithms like Dijkstra's, Prim's, and "Top K elements" problems.
π§ Time complexity
- Top element access: $O(1)$
- Insertion: $O(\log N)$
- Removal of top: $O(\log N)$
π» Code example
cpp Standard#include <queue> #include <vector> // Max-heap (default) std::priority_queue<int> maxHeap; maxHeap.push(10); maxHeap.push(30); maxHeap.push(20); std::cout << maxHeap.top(); // 30 // Min-heap std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap; minHeap.push(10); minHeap.push(30); std::cout << minHeap.top(); // 10
β Common mistakes
- Default Behavior: Forgetting that it's a max-heap by default.
- Efficiency: Overusing it when a simple sorted vector or
std::setmight suffice. - Updating Elements: C++
std::priority_queuedoes not support updating an internal element (you must re-insert or use a different container).