Structs as Values
The values in a map can be of any type: strings, vectors, and also structs. A bestiary, a book of monsters, can keep the health and attack of each kind of monster under its name:
#include <iostream>
#include <map>
#include <string>
struct Monster {
int health;
int attack;
};
int main() {
std::map<std::string, Monster> bestiary = {
{"Orc", {40, 8}},
{"Slime", {10, 2}},
{"Troll", {80, 12}}
};
bestiary["Slime"].attack += 1;
std::cout << "Troll health: " << bestiary["Troll"].health << std::endl;
for (const auto& [name, monster] : bestiary) {
std::cout << name << ": attack " << monster.attack << std::endl;
}
return 0;
}This prints:
Troll health: 80
Orc: attack 8
Slime: attack 3
Troll: attack 12Each element is the key and then the struct in curly braces, with its members in their order, as when you create a struct: {"Orc", {40, 8}}. bestiary["Troll"] is the whole struct, so bestiary["Troll"].health is one of its members, and you can change it like any member. In the loop, monster is a const reference to the struct. The name of a monster is the key now, so the struct Monster doesn't need a member for it.
What do square brackets add for a missing key when the values aren't numbers? An "empty" value of their type: an empty string for strings, an empty vector for vectors, and for a struct, a struct whose members have their default values, or 0 when they have none. bestiary["Dragon"] would add a dragon with 0 health and 0 attack, which is hardly what you want, so read with at() unless you mean to add.
A map of vectors works the same way. In std::map<std::string, std::vector<std::string>> drops;, the statement drops["Orc"].push_back("axe"); adds the key "Orc" with an empty vector the first time, and then puts "axe" into that vector.
Instructions
- 1
Print the bestiary, one line for each monster:
Orc: health 40, attack 8 Slime: health 10, attack 2 Troll: health 80, attack 12Keep the lines of the bestiary and the line with
waveas they are: the exercise will also try other monsters. - 2
The monsters in
waveattack Aria all at once. Below, add up the attack of every monster in the wave, as the bestiary gives it, and printDamage per round: 12.