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::set might suffice.
  • Updating Elements: C++ std::priority_queue does not support updating an internal element (you must re-insert or use a different container).