Changing a Vector in a Function
In the Functions lesson, you saw that a function gets a copy of a vector. When it changes the copy, the vector of the code that called it stays the same. Now you know how to change that: make the parameter a reference to a vector, std::vector<int>&.
#include <iostream>
#include <vector>
void addRoll(std::vector<int>& rolls, int roll) {
rolls.push_back(roll);
}
int main() {
std::vector<int> rolls = {4, 2};
addRoll(rolls, 6);
addRoll(rolls, 1);
std::cout << "Number of rolls: " << rolls.size() << std::endl;
return 0;
}This prints:
Number of rolls: 4Without the &, the function would add the rolls to its copy, and the program would print Number of rolls: 2.
Through a reference, you can also change the elements of a vector. This function doubles every number in the vector:
void doubleAll(std::vector<int>& numbers) {
for (int i = 0; i < numbers.size(); i++) {
numbers[i] = numbers[i] * 2;
}
}Watch out for the range-based for loop. This version doesn't change the vector, even though the parameter is a reference:
void doubleAll(std::vector<int>& numbers) {
for (int number : numbers) {
number = number * 2;
}
}In each pass of the loop, number is a copy of one element, just like a parameter passed by value. The loop doubles the copies, and the vector stays as it was. The program still compiles and runs without an error. When you want to change the elements in such a loop, add & here too:
void doubleAll(std::vector<int>& numbers) {
for (int& number : numbers) {
number = number * 2;
}
}Now, in each pass, number is a reference to one element of the vector, and whatever you do to number happens to the element. The index loop from the first example works just as well.
Instructions
The function addBonus should add bonus points to every player's score, but the program prints the original scores 12, 7 and 15. The function has two mistakes. First fix the parameter: the function must get a reference to the vector, not a copy of it. The program will still print the same numbers. Why?
Fix the loop in the function too, so that it changes the elements of the vector and not their copies. The program then prints the scores with the bonus, one per line: 17, 12 and 20.
Start programming for free
3/10