Chapter 15. Templates and std::unordered_map
In this final chapter, you will use a lookup table to track how many of each Event type happens in your game.
You will tally the frequency of each Event during the game and report back afterward.
The tally won’t add anything to the game itself, but it will show you another useful C++ container.
You will use a std::unordered_map to keep the frequencies per Event, and that means you need to write your own template to facilitate the lookup.
Adding lookup tables to your repertoire and knowing how to write templates will leave you with a firm grounding in a range of C++.
You can use the tally to check that you get the different Events with the probabilities you
requested.
You will also learn about defaulting the equality operator for your types and about the std::pair, and you’ll get the chance to write another visitor.
You’ve covered a lot of C++ now, so let’s finish up with a few last details.
I haven’t covered everything—C++ is a big language—but you know enough to write a whole program, and you know where to look things up.
Making a Lookup Table
Lookup tables are sometimes called dictionaries in other languages.
They are a type of associative container: a container that provides fast lookup.
A lookup table contains key-value pairs.
Your key will be an Event, and the value will be the tally.
C++ provides two types that map unique keys to unique values.
The older container is the std::map, defined in the <map> header. This container ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access