Top Score
Who did best in the test? You know how to find the largest value in a vector from the lesson on loops: remember the first element, and in a loop, check whether any of the others is larger. But this time, knowing the highest score isn't enough. The teacher wants to know who it is, and the name is in a different vector. So remember the index of the best student. With it, you can get both the name and the score:
std::vector<std::string> athletes = {"Amy", "Ben", "Chloe"};
std::vector<int> jumps = {412, 455, 430};
int longest = 0;
for (int i = 1; i < jumps.size(); i++) {
if (jumps[i] > jumps[longest]) {
longest = i;
}
}
std::cout << "Longest jump: " << athletes[longest] << ", " << jumps[longest] << " cm" << std::endl;Longest jump: Ben, 455 cmThe variable longest starts at 0, at the first element, so the loop can start at index 1. Comparing with > (not >=) means that in a tie, whoever comes first in the vector wins.
Turn this into a function, bestStudent(), that returns the index. A common mistake is to return the highest score instead of the index. Then names[48] is an element far past the end of a vector that has only 5 elements, and the program prints nonsense or crashes.
In printResults(), you'll need the index twice: for the name and for the score. So store it in a variable, for example int index = bestStudent(scores);, and the function is called only once.
Instructions
Above printResults(), write a function int bestStudent(const std::vector<int>& scores) that returns the index of the element with the highest score.
In printResults(), under the average, print the name and the score of the best student:
Best: Finn (48 points)Start programming for free
4/7