A Vector of Objects
A dungeon has more than one monster. Objects go into a vector like any other values, and each element is written as a call of the constructor:
std::vector<Monster> monsters = {
Monster("Goblin", 30),
Monster("Orc", 50),
Monster("Bat", 8)
};
monsters.push_back(Monster("Slime", 12));As with structs, braces work too, {"Goblin", 30}, because they call the constructor. But Monster("Goblin", 30) shows what you are creating.
The loops work as with structs, and the & matters just as much. To change the monsters, the loop's variable has to be a reference:
for (Monster& monster : monsters) {
aria.hit(monster);
}Without the &, monster would be a copy of each element, the hero would hit the copies, and the monsters in the vector would keep all their health, without any error.
A loop that only reads takes a const reference, for (const Monster& monster : monsters). Through it, you can call only const methods, such as isAlive() and printStatus(). If you tried to hit the monsters in such a loop, the compiler would stop you: aria.hit(monster) ends with the error binding reference of type 'Monster' to value of type 'const Monster' drops 'const' qualifier. The method hit wants a monster it may change, and the loop promised not to change it.
Instructions
- 1
Aria attacks the whole group. Above the loop that prints the monsters, write a loop in which she hits each monster once. The program prints
Goblin: health 10,Orc: health 30,Bat: health 0andTroll: health 60, one per line. Keep the lines that create Aria and the monsters as they are: the exercise will also try other values. - 2
Below the print loop, count the monsters that are still alive, in a loop that only reads them, and print
Monsters left: 3.