Returning a Struct
A function can return a struct. return gives back only one value, but that value can have several members. This function makes a monster for a level of the dungeon: the deeper the level, the stronger the monster.
#include <iostream>
#include <string>
struct Monster {
std::string name;
int health;
int attack;
};
// A monster for the given level of the dungeon
Monster makeMonster(const std::string& name, int level) {
Monster monster = {name, 20 + level * 10, level * 2};
return monster;
}
int main() {
Monster bat = makeMonster("Bat", 1);
Monster dragon = makeMonster("Dragon", 10);
std::cout << bat.name << ": " << bat.health << ", " << bat.attack << std::endl;
std::cout << dragon.name << ": " << dragon.health << ", " << dragon.attack << std::endl;
return 0;
}This prints:
Bat: 30, 2
Dragon: 120, 20The return type before the function's name is Monster. The function creates a local variable, fills it in and returns it, and the caller gets a copy: bat in main is a monster of its own. You can also return the braces right away, without the variable: return {name, 20 + level * 10, level * 2};. C++ knows from the return type that they make a Monster.
In the lesson on references, a function gave back two results through two reference parameters. With a struct, it's often simpler: put the results into one struct and return it.
A function can also return one of the structs in a vector, as a copy. That's how you will find the strongest monster in the task. It's the largest-value pattern from the lesson on loops, only you remember a whole monster instead of one number: start with the first monster, and whenever a stronger one comes along, remember that one instead. best = monster; copies the whole monster, all its members at once.
Instructions
- 1
In place of the comment, write a function
Monster strongest(const std::vector<Monster>& monsters)that returns the monster with the highest attack. Inmain, store what it returns in a variableboss, and printStrongest: Troll (health 80, attack 12)from its members. Keep the lines of the vector as they are: the exercise will also try other monsters. - 2
Below
strongest, write a functionMonster makeMonster(const std::string& name, int level)that returns a monster with healthlevel * 15and attacklevel * 3. - 3
At the end of
main, add a dragon of level 10 to the vector withmonsters.push_back(makeMonster("Dragon", 10));and print the strongest monster again. The last line isStrongest: Dragon (health 150, attack 30).