8 Unordered maps and coroutines

 

This chapter covers

  • Unordered maps
  • Hashes
  • Coroutines

In this chapter, we will make a matching-pennies game. The game has two players: us and the computer. We each have a coin and choose heads or tails. If the computer matches our choice, we lose. If the computer’s choice differs, we win. We can use a random distribution for the computer’s guess, so we don’t need much code for the first game.

Once we have the initial matching-pennies game working, we’ll see whether the computer can predict our guess by building a mind-reading machine. To be honest, the computer won’t really be able to read our minds. Claude E. Shannon wrote a short paper in 1953 called “A Mind-Reading (?) Machine” (see http://mng.bz/vPDp). The question mark in the title is deliberate. The game has been used for thought experiments in game theory and for psychology research. The mind reader needs to keep track of what has previously happened, so we’ll use the std::unordered_map to track the state. In chapter 7, we used an std::map. In this chapter, we’ll use an std::unordered_map for further practice. As we noted in chapter 7, the std::map needs an operator< defined for its keys. The std::unordered_map requires a hash and an equality operator, so we’ll learn about std::hash too. The computer will use the state to predict our next choice. When we’re done, we’ll wrap the code in a coroutine for extra practice.

8.1 Randomly generated matching pennies

8.2 Matching pennies using an unordered_map

8.2.1 Unordered containers and std::hash

8.2.2 Using an unordered_map to make a prediction

8.2.3 The mind reader game

8.3 Coroutines

8.3.1 How to make a coroutine

8.3.2 A coroutine function

8.3.3 The coroutine’s return object

8.3.4 RAII and the rule of zero

8.3.5 Filling in the promise_type

8.3.6 Filling in the Task type

8.3.7 A coroutine mind reader

Summary