Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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. 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 0 and Troll: 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. 2

    Below the print loop, count the monsters that are still alive, in a loop that only reads them, and print Monsters left: 3.

Back

9/11

  1. 1. Methods
  2. 2. Methods That Change the Object
  3. 3. Private and Public Members
  4. 4. Getters and const Methods
  5. 5. Constructors
  6. 6. Quiz: Constructors
  7. 7. Rules in One Place
  8. 8. Objects as Parameters
  9. 9. A Vector of Objects
  10. 10. Quiz: Damage in a Loop
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.