Learn C++ STL

Lesson 5 of 9 · unordered_set and unordered_map: Hashing, Collisions and the Anti-Hash Test

Module 10 · unordered_set and unordered_map: Hashing, Collisions and the Anti-Hash Test

Under the Hood: Chained Buckets, Prime Counts and the Anti-Hash Test

ProReading

Kenji's contest solution kept its numbers in an unordered_set<long long>, and 85,000 random numbers went in within 10 ms. After the contest, a rival added one test: 85,000 numbers, every one a multiple of 85,229. On that test the same inserts took 15.5 to 19.2 seconds on Compiler Explorer. Same container, same count, over a thousand times slower. Maria asks the question this lesson answers: "But why would the multiples of one number break a hash table?"

Checking what this lesson needs for you…

What is inside Under the Hood: Chained Buckets, Prime Counts and the Anti-Hash Test

  1. One list through every node, and buckets that point into it
  2. A node: one link, the key, and sometimes the hash code
  3. Growing: a prime count at least twice as large
  4. A rehash relinks every node and copies none
  5. The performance lab: unordered_map against map
  6. The anti-hash test: keys aimed at one bucket
  7. Two defences: a seed nobody knows, or a tree
  8. Why a fixed hash, however clever, is no defence