Top Score
Who did best in the test? In the lesson on loops, you found the largest value with a loop of your own. The lesson on algorithms gave you a ready-made function for it: std::max_element from <algorithm>. It gets a range, from begin() to end(), and returns an iterator that points to the largest element.
To compare two students, though, it has to know what "larger" means here: more points. So give it a lambda that gets two students and returns true when the first one has fewer points than the second: the question "is a smaller than b?". An example with long jumps:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
struct Jump {
std::string athlete;
int length;
};
int main() {
std::vector<Jump> jumps = {{"Amy", 412}, {"Ben", 455}, {"Chloe", 430}};
auto longest = std::max_element(jumps.begin(), jumps.end(), [](const Jump& a, const Jump& b) { return a.length < b.length; });
std::cout << "Longest jump: " << longest->athlete << ", " << longest->length << " cm" << std::endl;
return 0;
}Longest jump: Ben, 455 cmThe iterator longest works like a pointer: *longest is the element it points to, and longest->athlete is short for (*longest).athlete. When several elements are equally large, std::max_element returns the first of them.
Watch the direction of the comparison. With a.score > b.score, the lambda says that more points are "smaller", and you get the student with the lowest score: Best: Jack (14 points). Without a lambda, std::max_element tries to compare two students with <, which C++ can't do with a struct. The error then comes from inside the library:
/usr/include/c++/v1/__algorithm/comp.h:42:18: error: invalid operands to binary expression ('const Student' and 'const Student')Put it in a function, bestStudent(), that returns the best student. return *best; returns a copy of the element that the iterator points to, just as functions returned structs in the lesson on structs. In printResults(), store the result in a variable, Student best = bestStudent(students);, and print its name and score.
#include <algorithm> goes at the top, under <iostream>. Here, the program compiles even without it, because <iostream> happens to bring it in, but with another compiler, it might not. So include what you use.
Instructions
- 1
Between
average()andprintResults(), write a functionStudent bestStudent(const std::vector<Student>& students)that finds the student with the highest score withstd::max_elementand a lambda, and returns that student. Add#include <algorithm>at the top. - 2
In
printResults(), under the average, print the name and the score of the best student:Best: Finn (48 points)