DEV Community

Nithya Dharshini official
Nithya Dharshini official

Posted on

Learning set, unordered_set, and priority_queue in C++

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 << " ";
Enter fullscreen mode Exit fullscreen mode

Output

1 2 3

Enter fullscreen mode Exit fullscreen mode

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 << " ";
Enter fullscreen mode Exit fullscreen mode

Output

2 3 1   // order not guaranteed

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

Min Heap

priority_queue<int, vector<int>, greater<int>> minHeap;

Enter fullscreen mode Exit fullscreen mode

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)