Small Steps V — Making Your Own Types
Storing several grouped values
Store several grouped values.
What you will learn
A type you create can also be an array element. Array<Player> holds information about several players.
Try it
Example · example2.cpp
struct Player
{
String name;
int score;
};
void small_main()
{
Array<Player> players = {
{"Alex", 800},
{"Mina", 1200},
{"Sam", 950}
};
int best = 0;
for (int i = 1; i < players.length(); i = i + 1)
if (players[i].score > players[best].score)
best = i;
print("Winner: ", players[best].name);
}
players[i].score is the score of player i. Reuse the method for finding a maximum's position, then print that player's name at the end.
The expected result is Winner: Mina. Change the scores and check that the winner changes.
Exercise
Put three Players with name and score in an Array and print the name of the Player with the highest score.
Exercise starter · exercise2_starter.cpp
struct Player
{
String name;
int score;
};
void small_main()
{
Array<Player> players = {
{"A", 10},
{"B", 35},
{"C", 20}
};
// find and print the best player's name.
}
Hint
Use the lesson's best-index pattern.
show solution
struct Player
{
String name;
int score;
};
void small_main()
{
Array<Player> players = {
{"A", 10},
{"B", 35},
{"C", 20}
};
int best = 0;
for (int i = 1; i < players.length(); i = i + 1)
if (players[i].score > players[best].score)
best = i;
print(players[best].name);
}