Summary
In this lesson, you learned that:
- A map stores values under keys. It needs
#include <map>, and its angle brackets hold the type of the keys and then the type of the values:std::map<std::string, int> prices = {{"sword", 50}, {"potion", 10}};. Each element is a key with its value, and each key is in the map only once. prices["sword"]reads the value stored under a key.prices["sword"] = 45;changes it, or adds the key when it isn't there yet.+=,-=,++and--work on values too, andsize()gives the number of keys.for (const auto& [item, price] : prices)goes through all the elements.autolets the compiler work out the type, and the names in square brackets are for the key and the value. Withauto&, the loop can change the values, but never the keys.- A
std::mapkeeps its keys sorted. Strings are sorted by the codes of their characters, so uppercase letters come before lowercase ones, and letters with accents afterz. - Square brackets add a missing key with 0, so a typo in a key makes a new key instead of an error.
count(key)gives 1 or 0 and adds nothing.at(key)stops the program when the key is missing:std::out_of_range: map::at: key not found. - Counting is one line in a loop:
counts[item]++;. erase(key)removes an element, andempty()says whether the map has no elements left.- A function gets a map as a const reference to read it (
const std::map<std::string, int>& prices) and as a reference to change it. Square brackets don't compile on a const map, so read it withat()andcount(). - The values can be structs or vectors:
bestiary["Troll"].health. For a missing key, square brackets add an "empty" value of the type. std::unordered_map(#include <unordered_map>) is used the same way, but keeps its keys in no order you can rely on. It is usually faster for big maps. When you need the order, or aren't sure, usestd::map.
In the next lesson, Algorithms and Lambdas, you will let ready-made functions of the standard library do common work for you: sort a vector, find its largest element, or count the elements that match a condition.
Instructions
- 1
Let's practice. Count the loot from the arena in a map
counts, and print each kind of loot with its number:bread: 1 gem: 2 potion: 2Keep the lines of
pricesand the line withlootas they are: the exercise will also try other data. - 2
The shop buys only the kinds of loot that are in
prices. In place of the comment abovemain, write a functionlootValuethat getscountsandprices, both as const references, and returns how much gold the shop pays for all the loot: for each kind it buys, the number times the price. Print the result below the list:The shop pays: 116.