Missing Keys
What happens when you read a key that isn't in the map? With a vector, an index past the end gives you a meaningless number. A map does something else: square brackets add the missing key with the value 0, and give you that 0:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> inventory = {
{"bread", 2},
{"potion", 3}
};
std::cout << "Potions: " << inventory["poiton"] << std::endl;
std::cout << "Different items: " << inventory.size() << std::endl;
return 0;
}This prints:
Potions: 0
Different items: 3A typo in a key isn't an error. The program runs, says that Aria has no potions, and her inventory now has a third item, "poiton". Uppercase and lowercase letters matter as well: "Potion" and "potion" are two different keys. Adding a missing key with 0 is handy when you count, as you will in the next exercise. But when you only want to look, it's a trap.
Two methods look without adding anything. count(key) tells you whether the key is in the map: it gives 1 when it is, and 0 when it isn't. Keys are unique, so it's never more than 1:
if (inventory.count("helmet") == 0) {
std::cout << "No helmet" << std::endl;
}at(key) reads a value like square brackets do. But when the key is missing, it stops the program, just as at() does with an index outside a vector:
std::cout << "Potions: " << inventory.at("potion") << std::endl;
std::cout << "Helmets: " << inventory.at("helmet") << std::endl;
std::cout << "End" << std::endl;This prints Potions: 3, and then the program stops with an error:
std::out_of_range: map::at: key not found
RuntimeError: unreachableThe first line says that a key wasn't found. End is never printed.
So which one do you use? Square brackets when you add or change a value, or when 0 is the right answer for a missing key. count() when you want to ask first. And at() when the key must be there: if it isn't, your program has a bug, and it's better to stop right away than to go on with a 0. Newer versions of C++ also have contains(key), which you will see online, but the compiler here uses C++17, which doesn't have it yet: no member named 'contains' in 'std::map<std::string, int>'.
Instructions
- 1
Aria goes shopping with a list. Run the program: it says that a sword costs 0, and the shop suddenly has 4 items, because the square brackets added the sword to the map. Change the loop so that for an item the shop doesn't have, it prints
sword: not in the shop(with the item's name) and adds nothing. Usecount(). The program prints:potion: 15 sword: not in the shop bread: 3 Items in the shop: 3Keep the line with
shoppingListas it is: the exercise will also try another list. - 2
Add up the prices of the items Aria can buy, and print the total on the last line:
Total: 18. You know that these items are in the map, so you can read their prices withat().