A Vector of Structs
One monster is one struct. For a whole dungeon full of them, you already know what to use: a vector. A struct is a type like any other, so std::vector<Monster> is a vector of monsters:
#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},
{"Troll", 80, 12},
};
monsters.push_back({"Bat", 8, 2});
std::cout << "The second monster: " << monsters[1].name << std::endl;
for (const Monster& monster : monsters) {
std::cout << monster.name << " (" << monster.health << ")" << std::endl;
}
return 0;
}This prints:
The second monster: Orc
Goblin (30)
Orc (50)
Troll (80)
Bat (8)Each element is a monster in curly braces, as you would write it after Monster goblin =, and commas separate the elements. push_back takes a new monster the same way, or a Monster variable: monsters.push_back(goblin);.
Read monsters[1].name from left to right: element 1 of the vector, which is the orc, and then its member name. The other way round, monsters.name[1], doesn't work. A vector has no member name, and the compiler says so:
main.cpp:19:53: error: no member named 'name' in 'std::vector<Monster>'Look at the loop: for (const Monster& monster : monsters). It's the loop over strings from the lesson on strings, for (const std::string& item : inventory), only with monsters. A monster with a string inside is bigger than a number, and with Monster monster, the loop would copy each monster before using it. const Monster& reads each monster right in the vector, and the const makes sure that the loop doesn't change it. An index loop works as well: monsters[i].name.
With a struct Song, the playlist from the checkpoint would be one vector, std::vector<Song>, and each title would stay with its length, whatever you add or remove.
Instructions
- 1
With a loop, print every monster in the vector on a line of its own:
Goblin: health 30, attack 5,Orc: health 50, attack 8andTroll: health 80, attack 12. Keep the lines of the vector as they are: the exercise will also try other monsters. - 2
Between the vector and the loop, add a bat to the vector with
push_back: its name isBat, its health8and its attack2. The loop then prints it last:Bat: health 8, attack 2. - 3
Below the loop, add up the health of all the monsters and print it once:
Total health: 168.