7 Associative containers and files

 

This chapter covers

  • Filling and using associative containers
  • Pairs and tuples
  • Reading from files
  • Random samples

We have used vectors several times now but haven’t used an associative container yet. An associative container holds key-value pairs, giving us a lookup table or dictionary. In this chapter, we will use dictionaries to create a game of answer smash. We’ll provide two clues, each a definition of a word. The end of the first word will overlap with the start of the next word, giving the answer. For example, a vector is a “sequential container supporting dynamic resizing,” and a torch could be defined as a “lit stick carried in one’s hand,” so smashing together the words vector and torch gives the answer vectorch.

We’ll start by storing a dictionary in an std::map defined in the map header, which existed before C++11, and then consider other types of associative containers too. We will use the newer std::unordered_map in the next chapter, so using std::map in this chapter will be a useful revision, and we will learn about an std::pair and the more general std::tuple on the way. We will start with hardcoded dictionaries and read data from a file afterward using a random sample to create variety when we play the game.

7.1 Hardcoded answer smash

7.1.1 Creating and using an std::map

7.1.2 Pairs, tuples, and structured bindings

7.1.3 A simple answer smash game

7.2 Associative containers

7.2.1 The map type in more detail

7.2.2 Using lower and upper bound to find a key more efficiently

7.2.3 Multimaps

7.3 File-based answer smash

7.3.1 Loading data from a file

7.3.2 Picking a word randomly using std::sample

7.3.3 Answer smash