A function that receives a vector by value gets its own copy of the collection. That can be useful when it needs a private copy, but a reporting function usually just needs to read the original. A const reference expresses that intent.
In const std::vector<int>& values, std::vector<int> names the collection type, & makes the parameter a reference, and const prevents changes to the vector through this parameter. The parameter is another name for the caller's vector during the call, without copying all its elements.
#include <vector>
#include <iostream>
int sum(const std::vector<int>& values) {
int result = 0;
for (int value : values) {
result += value;
}
return result;
}
int main() {
std::vector<int> minutes{6, 9};
std::cout << sum(minutes) << '\n';
}
The caller still writes an ordinary call, sum(minutes). There is no extra & at the call site. The result is fifteen, and the vector is unchanged. const restricts access through the parameter; it does not permanently turn the caller's variable into a constant.
The loop's int value remains a small by-value copy. That is a different decision from copying the entire vector on function entry. When loop elements are larger, a range loop can use const std::string& word to read each string without copying it. The same two pieces mean read-only access and another name for the current element. We will use that pattern with records later.
The const-reference parameter is already supplied; your edits belong inside the helper. First replace the temporary -1 initializer with the starting value for a sum. The empty-vector call is useful here: its loop makes no visits, so it returns exactly that starting value. Then add the loop update to handle a nonempty vector. This second result depends on completing the initialization first.
total to zero so an empty vector returns zero. Expect Empty total: 0.value to total in the loop. With Task 1 complete, expect Stock total: 15.Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.