liveBook · Manning

Unordered_map

As explained in Learn C++ by Example

unordered_map is an unordered associative container that stores key-value pairs and supports lookup by key.

An unordered_map stores key-value pairs and locates values through a hash table. In a matching-pennies mind reader, it records game states so the computer can predict a later choice. section 8.0

Use an unordered_map by understanding three cooperating parts:

  • Buckets hold elements, while a hash function selects the bucket associated with a key. Collisions are allowed, but a better hash can improve performance. section 8.2.1
  • The container template takes key, value, hash, and key-equality types; std::hash and std::equal_to provide the defaults. section 8.2.1
  • A user-defined key must support equality and normally needs a hash implementation. A tuple key can use equality directly, but requires a custom std::hash specialization. section 8.2.1

A state table for matching pennies

Represent each state as {penultimate outcome, choice, last outcome}, then map it to the player’s last two choices. An initial table can contain all eight combinations, each paired with an unset choice pair. As turns accumulate, matching outcomes support a prediction; when the state has no useful matching history, the computer chooses randomly. section 8.2 section 8.2.1

Table 8.1 The eight possible states in the pennies game (view table figure)

Penultimate outcome

Choice

Last outcome

Lose

Same

Lose

Lose

Same

Win

Lose

Change

Lose

Lose

Change

Win

Win

Same

Lose

Win

Same

Win

Win

Change

Lose

Win

Change

Win

Browse the eight possible combinations of the two recorded outcomes and whether the player changed or repeated a choice. section 8.2

How Learn C++ by Example covers it

How deep it goes
Explains buckets, collisions, default policies, tuple equality, custom hashing, and collision checks.
Examples
Demonstrates an eight-state matching-pennies table keyed by a tuple and mapped to pairs of previous choices.
What it assumes
Assumes basic C++ containers and templates while teaching hash functions, equality policies, buckets, and collisions.
What you can do after
Build a state table with std::unordered_map and support tuple keys by specializing std::hash.
How it connects
Connects unordered_map with hash tables, std::hash, std::equal_to, std::map, tuples, and user-defined key types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.