Changing Structs in a Loop
In the lesson on references, a loop over a vector of numbers didn't change it, because each int number was a copy. It's the same with structs, and it's an easy mistake to make. This loop should hit every monster with a fire spell:
for (Monster monster : monsters) {
monster.health -= 20;
}It compiles and runs without an error, but the monsters in the vector keep all their health. In each pass, monster is a copy of one monster: the spell burns the copy, and the copy is gone at the end of the pass.
To change the monsters in the vector, make the loop's variable a reference, with & and without const:
#include <iostream>
#include <string>
#include <vector>
struct Monster {
std::string name;
int health;
int attack;
};
int main() {
std::vector<Monster> monsters = {
{"Goblin", 30, 5},
{"Orc", 50, 8},
};
for (Monster& monster : monsters) {
monster.health -= 20;
}
for (const Monster& monster : monsters) {
std::cout << monster.name << ": " << monster.health << std::endl;
}
return 0;
}This prints:
Goblin: 10
Orc: 30Now monster is the monster in the vector under another name, and the spell hits it. An index loop changes the vector too, because monsters[i] is the element itself: monsters[i].health -= 20;.
So a loop over structs can be written in three ways:
for (const Monster& monster : monsters)reads the monsters without copying them.for (Monster& monster : monsters)changes them.for (Monster monster : monsters)works with copies. You will rarely need that.
If you write const out of habit and then try to change the monster, the compiler stops you:
main.cpp:18:24: error: cannot assign to variable 'monster' with const-qualified type 'const Monster &'That's a useful error: the loop promised not to change anything.
Instructions
- 1
The fire spell should take 20 health from every monster, but the program prints their health unchanged. Fix the spell's loop so that it changes the monsters in the vector. The program then prints
Goblin: 10,Slime: -8andTroll: 60. Keep the lines of the vector as they are: the exercise will also try other monsters. - 2
Health shouldn't go below 0. In the spell's loop, after the damage, set a monster's health to
0when it has fallen below zero. The slime then has0health:Slime: 0. - 3
Below the loop that prints the monsters, count the ones that still have more than 0 health, and print the count once:
Still standing: 2.