Bonus Points
The teacher has found out that one question in the test was worded wrong. So everyone gets 3 bonus points. But nobody can have more than 50 points, because that's the most the test could give.
This time, the function changes the data. So it gets the vector as a reference without const: std::vector<Student>&. Then it works with the vector from main() directly, and the changes stay in it after the function ends. Its loop goes through the students as references without const too, Student&. Each student is then the element in the vector, and a change to its score changes the vector. For example, a game that gives every player one more life:
#include <iostream>
#include <string>
#include <vector>
struct Player {
std::string name;
int lives;
};
void addLife(std::vector<Player>& players) {
for (Player& player : players) {
player.lives++;
}
}
int main() {
std::vector<Player> players = {{"Amy", 2}, {"Ben", 3}};
addLife(players);
for (const Player& player : players) {
std::cout << player.name << ": " << player.lives << std::endl;
}
return 0;
}Amy: 3
Ben: 4Common mistakes:
- Without the
&in the loop,for (Student student : students), eachstudentis a copy. The loop changes the copies, and the results still show the old scores. Without the&in the parameter, the same happens: the function changes a copy of the whole vector. - With
const, the compiler doesn't allow the change:
main.cpp:70:23: error: cannot assign to variable 'student' with const-qualified type 'const Student &'The call goes in main(), above printResults(students): first the scores change, then they're printed. The other way round, the old scores would be printed.
Instructions
- 1
Under
printResults()(abovemain()), write a functionvoid addPoints(std::vector<Student>& students, int bonus)that addsbonusto the score of each student in a loop overStudent&. - 2
In
main(), above the call ofprintResults(), addaddPoints(students, 3);. Every student now has 3 more points, and the results start like this:TEST RESULTS Adam: 45 points, grade A Emma: 41 points, grade BAdam has exactly 45 points, so he gets an A. If he has a B, check that the condition for an A in
grade()uses>=. If the scores haven't changed, an&is missing, in the parameter or in the loop. Finn now has 51 points out of 50. You'll fix that in the next step. - 3
Change
addPoints(): if a student has more than 50 points after the addition, set their score to50. Then the results look like this:TEST RESULTS Adam: 45 points, grade A Emma: 41 points, grade B Finn: 50 points, grade A Jack: 17 points, grade F Lucy: 30 points, grade C Average score: 36.6 Best: Finn (50 points) Ranking: Finn, Adam, Emma, Lucy, JackIf Lucy with 30 points has a D, check the
>=in the condition for a C.