When to Use Which STL Container (Interview Thinking)
While learning C++ STL, three containers often appear in interview problems:
- set
- unordered_set
- priority_queue
They may look similar at first, but each solves different problem types.
This article explains how they work, their complexities, and when to choose each one.
1️⃣ set — Unique + Sorted Data
What it does
Stores unique elements
Maintains sorted order
Implemented using a self-balancing BST (Red-Black Tree)
Example
set<int> s = {3, 1, 2, 2};
for (int x : s) cout << x << " ";
Output
1 2 3
Complexity
Insert / Find / Delete: O(log n)
Space: O(n)
When to use set
✔ Need sorted unique values
✔ Order matters
✔ Predictable performance
2️⃣ unordered_set — Fast Lookup, No Order
What it does
Stores unique elements
Uses hashing
Does not maintain order
Example
unordered_set<int> us = {3, 1, 2, 2};
for (int x : us) cout << x << " ";
Output
2 3 1 // order not guaranteed
Complexity
Average: O(1)
Worst case: O(n) (hash collisions)
Space: O(n)
When to use unordered_set
✔ Only uniqueness matters
✔ Need fast insert/search
✔ Order not required
3️⃣ priority_queue — Always Gives Best Element
What it does
Retrieves max or min element efficiently
Implemented using a heap
Default is max-heap
Example (Max Heap)
priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(5);
cout << pq.top(); // 5
Min Heap
priority_queue<int, vector<int>, greater<int>> minHeap;
Complexity
Push / Pop: O(log n)
Top: O(1)
Space: O(n)
When to use priority_queue
✔ Need kth largest / smallest
✔ Repeated max/min extraction
✔ Scheduling & greedy problems
Top comments (0)