Unordered Maps
The standard library has a second kind of map, std::unordered_map, from #include <unordered_map>. You use it just like std::map: square brackets, at(), count(), erase(), size(), empty() and the loop with auto all work the same. The difference is in its name: it doesn't keep its keys in order.
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> gold = {
{"Aria", 120},
{"Ben", 80},
{"Cleo", 200}
};
gold["Sam"] = 50;
for (const auto& [player, coins] : gold) {
std::cout << player << ": " << coins << std::endl;
}
return 0;
}This prints:
Ben: 80
Sam: 50
Cleo: 200
Aria: 120The loop went through the players neither sorted nor in the order in which they were added. And you can't rely on this order either: with another compiler, or after adding more keys, it can be different. So never write a program whose result depends on the order of an unordered map. A sum, a count or the largest value come out the same in any order.
In return, an unordered map is usually faster, mainly when it is big. To find a key, std::map compares it with other keys, the way you look up a word in a dictionary: open it in the middle, see whether the word comes before or after, and go on in that half. std::unordered_map calculates from the key itself where its value is stored, and looks right there.
So which one do you pick?
std::mapwhen you need the keys in order, for example to print a sorted list, and whenever you aren't sure. With a few dozen keys, you won't notice any difference in speed.std::unordered_mapwhen you only add, look up and count, the order doesn't matter, and there is a lot of data: the players of an online game, or the words of a long book.
As with vectors, a program sometimes compiles without #include <unordered_map>, because another #include brings it in. Don't rely on that, and always write it.
Instructions
- 1
The game server will have thousands of players, and it only looks up their gold, so it doesn't need their names in order. Change the map into a
std::unordered_map: replace#include <map>with#include <unordered_map>, and change the type ofgold. The program still printsPlayers: 4. - 2
Below, add up the gold of all players with a loop over the map, and print
Total gold: 450. For a sum, it doesn't matter in which order the loop goes through the players. Keep the lines of the map as they are: the exercise will also try other amounts.