Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

IntermediateSTL Containers ProgramsExample 6 of 10
unordered-map-and-set.cpp
1#include <iostream>
2#include <unordered_map>
3#include <unordered_set>
4#include <string>
5using namespace std;
6
7int main() {
8 // Unordered Map
9 unordered_map<string, int> wordCount;
10
11 wordCount["hello"] = 3;
12 wordCount["world"] = 2;
13 wordCount["c++"] = 5;
14 wordCount["programming"] = 1;
15
16 cout << "Unordered Map (Hash Map):" << endl;
17 for (const auto& pair : wordCount) {
18 cout << pair.first << ": " << pair.second << endl;
19 }
20
21 // Access
22 cout << "\nCount of 'c++': " << wordCount["c++"] << endl;
23
24 // Check if key exists
25 if (wordCount.find("hello") != wordCount.end()) {
26 cout << "'hello' found" << endl;
27 }
28
29 // Unordered Set
30 unordered_set<int> numbers;
31
32 numbers.insert(5);
33 numbers.insert(2);
34 numbers.insert(8);
35 numbers.insert(1);
36 numbers.insert(5); // Duplicate ignored
37
38 cout << "\nUnordered Set (Hash Set): ";
39 for (int num : numbers) {
40 cout << num << " ";
41 }
42 cout << endl;
43
44 // Check if element exists
45 if (numbers.find(8) != numbers.end()) {
46 cout << "Element 8 found" << endl;
47 }
48
49 // Size
50 cout << "Set size: " << numbers.size() << endl;
51
52 // 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;
56
57 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. 1

    Fill an unordered_map of word counts.

  2. 2

    Print it in bucket order.

  3. 3

    Read c++ with [] and check hello with find.

  4. 4

    Insert 5, 2, 8, 1, 5 into an unordered_set; size = 4.

  5. 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:

Uses hash function to map keys to buckets
O(1) average case operations
No automatic sorting
Faster than ordered containers for lookups

Key Features:

Fast access (O(1) average)
No sorted order
Hash-based storage
Collision handling

Unordered Map

Declaration:

unordered_map<string, int> wordCount;

Inserting:

wordCount["hello"] = 3;

wordCount["world"] = 2;

What happens here:

Key-value pairs stored in hash table
Fast lookup by key
No sorted order
O(1) average insert/find

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:

[] operator: creates if missing, returns value
find(): returns iterator, end() if not found
O(1) average case
Fast key-based access

Unordered Set

Declaration:

unordered_set<int> numbers;

Inserting:

numbers.insert(5);

numbers.insert(2);

numbers.insert(5); // Duplicate ignored

What happens here:

Stores unique elements
No sorted order
Fast membership testing
O(1) average insert/find

Hash Table Information

Bucket Information:

numbers.bucket_count() // Number of buckets

numbers.load_factor() // Average elements per bucket

What happens here:

Buckets: hash table slots
Load factor: elements/buckets ratio
Lower load factor = better performance
Rehashing occurs when load factor high

When to Use Unordered Containers

Good fits:

Fast lookups (order doesn't matter)
Hash-based operations
When sorting not needed
Performance-critical lookups
Dictionary-like structures

Example Scenarios:

Word frequency counting
Fast membership testing
Cache implementations
Symbol tables
Fast key-value lookups

Important Considerations

Performance:

Average case: O(1)
Worst case: O(n) (hash collisions)
Faster than map/set for lookups
Slower for range queries

No Sorting:

Elements not sorted
Cannot iterate in sorted order
Use map/set if sorting needed
Trade-off: speed vs order

Hash Collisions:

Multiple keys map to same bucket
Handled automatically
Can degrade to O(n) worst case
Good hash function important

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.