Hashing and STL Associative Containers

Lesson 13 of 20

Watch hash(key) fling keys into buckets, collide and chain — then meet the two STL maps behind the magic.

The big picture

Why O(1) lookup

Searching an array costs O(n) and a balanced tree costs O(log n). Hashing jumps straight to the answer: the key itself computes the slot it lives in.

Index math, not search

A hash function turns any key into a bucket number: hash(key) % buckets. Lookup becomes one jump — no scanning.

The hash function

Same key must always give the same slot, and different keys should spread out. key % 7 is the classic teaching hash.

Collisions happen

7 buckets cannot hold every key uniquely: 33 % 7 and 12 % 7 both land in slot 5. Chaining and probing are the two classic fixes.

std::unordered_map

The STL hash table: find, insert and erase in O(1) average. Keys come back in no guaranteed order.

std::map

The sorted cousin: a balanced tree with O(log n) operations and keys that iterate in order.

Load factor

size / bucket_count. Let it creep up and chains and probes get long — implementations rehash into a bigger table.