Post

std::unordered_map

std::unordered_map

std::unordered_map


Prerequisites


1. What is std::unordered_map?

std::unordered_map is an associative container that stores elements in key-value pairs, just like std::map.

1
std::unordered_map<Key, Value>
  • Keys are unique
  • No ordering of elements
  • Implemented using a Hash Table
  • Provides average O(1) time complexity

std::unordered_map is implemented using a Hash Table

How it works:
  1. Key → Hash function
  2. Hash → Bucket index
  3. Store value in that bucket

Multiple keys may land in the same bucket (collision)

Hash Collision

1
2
key1  hash  bucket 3
key2  hash  bucket 3

This is called a collision

Handling:
  • Chaining (linked list / nodes inside bucket)
  • Open addressing (implementation dependent)

Use it when:

  • You need fast lookup (O(1))
  • Order does not matter
  • You handle large datasets
✔️ Declaration
1
2
3
#include <unordered_map>

std::unordered_map<std::string, int> m;
✔️ Insertion
1
2
m["apple"] = 10;
m["banana"] = 20;

Or:

1
m.insert({"orange", 30});
1
m["new_key"];

If the key does not exist, it will be created automatically with a default value

✔️ Access
1
std::cout << m["apple"];  // 10

2. Functions

find
1
2
3
4
auto it = m.find("apple");

if (it != m.end())
    std::cout << it->second;
erase
1
m.erase("apple");
size
1
m.size();
clear
1
m.clear();
Iteration
1
2
for (const auto& pair : m)
    std::cout << pair.first << " : " << pair.second << "\n";

Order is not guaranteed

OperationComplexity
InsertO(1) average
SearchO(1) average
DeleteO(1) average
Worst CaseO(N)

Worst case happens when hash collisions occur

3. std::map vs std::unordered_map

Featureunordered_mapmap
StructureHash TableRed-Black Tree
OrderingNoneSorted
SpeedO(1) avgO(log N)
Worst CaseO(N)O(log N)
MemoryMoreLess

Use unordered_map when performance is critical

4. Common Mistakes

❌ Overusing operator[]
1
if (m["key"] == 0)  // ❌ Dangerous

Creates key if it doesn’t exist

✔️ Correct:

1
if (m.find("key") != m.end())
❌ Assuming order
1
2
3
4
for (auto& p : m)
{
    // ❌ Do NOT expect sorted order
}

5. Custom Hash Function

1
2
3
4
5
6
7
8
9
struct MyHash
{
    size_t operator()(int x) const
    {
        return x * 31;
    }
};

std::unordered_map<int, int, MyHash> m;
This post is licensed under CC BY 4.0 by the author.