Ranking
The teacher would also like to see the whole class in order, from the highest score to the lowest. That's a job for std::sort, with a lambda that says when one student goes before another: when they have more points, a.score > b.score.
But which vector should it sort? Not the one in main(): the results would then be printed in a different order too. And printResults() can't sort its students, because through a const reference, it can only read them. The compiler then reports errors from inside the library, the first of them this one:
/usr/include/c++/v1/__algorithm/sift_down.h:62:22: error: no viable overloaded '='Further down, a note with main.cpp names the line with your call of std::sort.
What you need is a copy. You know from the lesson on functions that a parameter without & gets a copy of the argument. Usually, that's something to avoid. Here, it's exactly what you want: a function printRanking(std::vector<Student> students) gets its own copy of the class, sorts it and prints it, and the vector in main() stays as it was.
The names go on one line, with a comma and a space between them, but not after the last one. So print the comma before each name, except before the first one, which has the index 0:
std::vector<std::string> colors = {"red", "green", "blue"};
for (int i = 0; i < colors.size(); i++) {
if (i > 0) {
std::cout << ", ";
}
std::cout << colors[i];
}
std::cout << std::endl;red, green, blueIf you see Ranking: Jack, Lucy, Emma, Adam, Finn, the lambda puts the lowest score first: it needs >, not <. And when two students have the same score, std::sort may put either of them first.
Instructions
- 1
Between
bestStudent()andprintResults(), write a functionvoid printRanking(std::vector<Student> students), without&, that sortsstudentswithstd::sortand a lambda from the highest score to the lowest. - 2
In
printRanking(), after sorting, printRanking:and the names in their new order on one line, with a comma and a space between them. CallprintRanking(students);at the end ofprintResults(). The results above it stay in the order of the vector, and a new line appears under the best student:Best: Finn (48 points) Ranking: Finn, Adam, Emma, Lucy, Jack