Looping over a Map
To print a whole inventory, go through the map with a range-based for loop, as you do with a vector:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> inventory = {
{"potion", 3},
{"water", 1},
{"bread", 2}
};
for (const auto& [item, count] : inventory) {
std::cout << item << ": " << count << std::endl;
}
return 0;
}This prints:
bread: 2
potion: 3
water: 1Each element of a map is a key together with its value. The first line of the loop has two new things:
autotells the compiler to work out the type by itself, here from the elements of the map. The exact type of an element has a long name, and you don't need to write it.autocan stand for other types too, but this course uses it only where the type is long, as here: a short type such asint, written out, tells the reader more.[item, count]gives the two parts of each element names of their own: the first one is the key, the second one the value. You choose the names, so pick ones that say what they hold.
const auto& works like const Monster& in a loop over a vector of structs: the loop doesn't copy the elements and can't change them. To change the values in the loop, leave out const. This loop doubles every value in the map:
for (auto& [item, count] : inventory) {
count = count * 2;
}A key can't be changed this way, not even with auto&: for item = "rope";, the compiler reports no viable overloaded '='.
Now look at the output again. The loop didn't go through the elements in the order in which they were written. A map keeps its keys sorted, so the loop always goes from the smallest key to the largest. Strings are sorted by the codes of their characters, as < compares them: alphabetically, but all uppercase letters come before all lowercase ones, so "Potion" would come before "bread". Letters with accents, such as é, come only after z.
Instructions
- 1
Print the shop's price list with a
forloop over the map: each item with its price, one line each. The program prints:bread: 3 helmet: 40 potion: 15 water: 2Keep the lines of the map as they are: the exercise will also try other items.
- 2
How much would everything in the shop cost? Add up all the prices, in the same loop or in another one, and below the price list print
Everything: 60.