
Unordered Set in C++
When learning C++, one of the most common questions is:
“How do I store unique items quickly without worrying about duplicates?”
The answer: unordered_set
Think of it as a magical bag where you can drop things in, but the bag will:
-
Throw out any duplicates.
-
Allow you to check if something is inside (super fast).
-
Not care about the order of things inside.
Introduction
An unordered_set
is a container in the C++ Standard Template Library (STL) that:
-
Stores only unique elements (duplicates not allowed).
-
Uses a hash table internally.
-
Provides average O(1) time complexity for common operations.
Syntax:
#include <unordered_set>
using namespace std;
unordered_set<int> mySet; // creates an empty set of integers
How Does It Work?
1. Bucket System
-
Elements are divided into buckets internally.
-
You can check which bucket an element goes into using:
cout << s.bucket(20);
- Useful for debugging performance.
2. Load Factor
-
Tells how full the hash table is.
-
Formula:
load_factor = size / number_of_buckets
.
3. Rehashing
- If the set becomes too crowded, it automatically rehashes (creates more buckets).
Operations on unordered_set
1. Inserting Elements
unordered_set<int> s;
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(20); // duplicate, ignored automatically
- Duplicate elements are ignored silently.
- Each element is stored only once.
2. Traversing Elements
for (int x : s) {
cout << x << " ";
}
Order is not guaranteed.
- You may see
30 20 10
or10 30 20
depending on how hashing works.
3. Checking Existence
if (s.find(20) != s.end())
cout << "20 exists in the set";
else
cout << "20 not found";
-
.find(x)
→ returns an iterator to the element if found, otherwises.end()
. -
Works in O(1) average time.
4. Erasing Elements
s.erase(10); // removes 10 if present
After this, 10
is gone from the set.
5. Size of Set
cout << "Size: " << s.size() << endl;
Full Example
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<int> s;
// Insert
s.insert(10);
s.insert(20);
s.insert(30);
s.insert(20); // ignored
// Print
cout << "Elements: ";
for (int x : s) cout << x << " ";
cout << endl;
// Search
if (s.find(20) != s.end()) cout << "20 is present\n";
// Erase
s.erase(10);
cout << "Size after erase: " << s.size() << endl;
}
Output (order may differ):
Elements: 30 20 10
20 is present
Size after erase: 2
Time and Space Complexity
Operation | Time Complexity (Average Case) | Time Complexity (Worst Case) | Space Complexity |
---|---|---|---|
Insert | O(1) | O(n) | O(n) |
Erase (Delete) | O(1) | O(n) | O(n) |
Search (find) | O(1) | O(n) | O(n) |
Size / Empty | O(1) | O(1) | O(1) |
Traverse (iterate) | O(n) | O(n) | O(n) |
Note:
-
Average case is super fast thanks to hashing.
-
Worst case
O(n)
happens only if too many elements land in the same bucket (hash collisions). -
Space is proportional to the number of elements
n
.
Common Mistakes
Mistake | What Happens |
---|---|
Assuming insertion order | Doesn’t work — elements are stored in random order, not in the order inserted. |
Expecting duplicates allowed | Not possible — duplicates are automatically ignored. |
Using in multithreading | Not thread-safe — wrap it with a mutex if used across multiple threads. |
Forgetting worst-case O(n) | In rare cases of heavy collisions, operations can degrade to linear time. |
When to Use unordered_set
Use unordered_set
when:
-
You want fast lookups (check if an element exists).
-
You need to store unique items only.
-
You don’t care about the order of elements.
-
You want an efficient alternative to manually checking for duplicates in arrays or vectors.
Examples:
-
Checking if a user ID is already registered.
-
Removing duplicates from a list.
-
Keeping track of visited nodes in a graph.
-
Fast membership testing in competitive programming.
Conclusion
unordered_set
is one of the most powerful and efficient STL containers in C++
It shines whenever you need:
-
Uniqueness (no duplicates)
-
Speed (O(1) average operations)
-
Simplicity (easy to use syntax)
Think of it as your go-to tool for problems where you only care whether something exists or not.
Whether it’s user IDs, roll numbers, visited states, or deduplicating data — unordered_set
is a must-have in your C++ toolkit.
Related Blogs
For More Amazing Blogs
Click here
Till then
Happy Coding!!!
3 Reactions
0 Bookmarks