Unordered Map and Set in C++
Use unordered_map and unordered_set in C++: hash tables with O(1) average lookups, unspecified order, ignored duplicates, buckets, and load factor.
1#include <iostream>2#include <unordered_map>3#include <unordered_set>4#include <string>5using namespace std;67int main() {8 // Unordered Map9 unordered_map<string, int> wordCount;1011 wordCount["hello"] = 3;12 wordCount["world"] = 2;13 wordCount["c++"] = 5;14 wordCount["programming"] = 1;1516 cout << "Unordered Map (Hash Map):" << endl;17 for (const auto& pair : wordCount) {18 cout << pair.first << ": " << pair.second << endl;19 }2021 // Access22 cout << "\nCount of 'c++': " << wordCount["c++"] << endl;2324 // Check if key exists25 if (wordCount.find("hello") != wordCount.end()) {26 cout << "'hello' found" << endl;27 }2829 // Unordered Set30 unordered_set<int> numbers;3132 numbers.insert(5);33 numbers.insert(2);34 numbers.insert(8);35 numbers.insert(1);36 numbers.insert(5); // Duplicate ignored3738 cout << "\nUnordered Set (Hash Set): ";39 for (int num : numbers) {40 cout << num << " ";41 }42 cout << endl;4344 // Check if element exists45 if (numbers.find(8) != numbers.end()) {46 cout << "Element 8 found" << endl;47 }4849 // Size50 cout << "Set size: " << numbers.size() << endl;5152 // Bucket information (hash table details)53 cout << "\nHash table info:" << endl;54 cout << "Number of buckets: " << numbers.bucket_count() << endl;55 cout << "Load factor: " << numbers.load_factor() << endl;5657 return 0;58}
Sample Output
Set size: 4
The second 5 was ignored.
Load factor: 0.5
4 elements ÷ 8 buckets in this run.
In this one
- How hashing gives average O(1) lookups
- Why iteration order is unspecified
- When to choose unordered_map over map
- What bucket_count and load_factor mean
How it works
- 1
Fill an unordered_map of word counts.
- 2
Print it in bucket order.
- 3
Read c++ with [] and check hello with find.
- 4
Insert 5, 2, 8, 1, 5 into an unordered_set; size = 4.
- 5
Print bucket_count and load_factor.
Edge cases
Order changes between compilers
Build with GCC and with Clang.
The pairs come out in a different order, and the bucket count differs. That is allowed by the standard.
Custom key type
unordered_set<pair<int,int>> s;
This does not compile because pair has no std::hash. Provide a hash function or use set.
What's going on
unordered_map and unordered_set are the hash-table versions of map and set. They give up sorted order in exchange for faster average lookups: insert, find, and erase are O(1) on average, against O(log n) for the tree-based containers.
A hash table works by running each key through a hash function to get a number, then using that number to pick a bucket. Lookup jumps straight to the right bucket instead of walking a tree.
The word-count map is filled and printed. The order you see is whatever the buckets happen to give. It is not insertion order and not alphabetical, and it differs between compilers. The sample shows one GCC run; Clang's libc++ prints the same pairs in a different order. Never write code that depends on it.
wordCount["c++"] reads a value, with the same rule as map: a missing key would be inserted with 0. find("hello") checks without inserting.
The unordered set gets 5, 2, 8, 1, 5. The duplicate is ignored, so the size is 4, and again the print order is unspecified.
The last two lines peek inside the hash table. bucket_count() is how many buckets exist and load_factor() is elements per bucket, here 4 ÷ buckets. When the load factor passes max_load_factor() (1.0 by default), the table grows and rehashes. Both numbers depend on the library: the sample shows 8 buckets and 0.5, while libc++ reports 5 buckets and 0.8.
Average O(1) is not a promise. If many keys land in the same bucket, operations degrade toward O(n). That rarely happens with built-in key types.
The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <unordered_map> is there because it provides unordered_map container class. <unordered_set> is there because it provides unordered_set container class. <string> is there because it provides string class for string keys. Leave one out and the compiler stops at the first name it does not recognize.
Understanding Unordered Containers
Hash Table Concept:
Key Features:
Unordered Map
Declaration:
unordered_map<string, int> wordCount;
Inserting:
wordCount["hello"] = 3;
wordCount["world"] = 2;
What happens here:
Accessing Unordered Map
Using [] Operator:
int count = wordCount["c++"];
Using find():
auto it = wordCount.find("hello");
if (it != wordCount.end()) {
// Key found
}
What happens here:
Unordered Set
Declaration:
unordered_set<int> numbers;
Inserting:
numbers.insert(5);
numbers.insert(2);
numbers.insert(5); // Duplicate ignored
What happens here:
Hash Table Information
Bucket Information:
numbers.bucket_count() // Number of buckets
numbers.load_factor() // Average elements per bucket
What happens here:
When to Use Unordered Containers
Good fits:
Example Scenarios:
Important Considerations
Performance:
No Sorting:
Hash Collisions:
return 0;
return 0; closes main and tells the operating system the program finished without an error.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does the standard say about unordered_map iteration order?
Pick an answer to check it.
Question 2
What is the average cost of find in unordered_set?
Pick an answer to check it.
Questions people ask
When should I use map instead?
When you need sorted output, the smallest or largest key, or range queries like lower_bound.
How do I make it faster for many inserts?
Call reserve(n) first so the table does not rehash repeatedly.
Is the order the same every run?
Usually on the same build, but nothing guarantees it.