C++ references, const, and auto
A reference is another name for an existing object. A function that takes std::vector<int>& works on the caller's vector and can change it. A parameter of type const std::vector<int>& also avoids the copy but promises not to modify it, so the compiler rejects accidental changes. Passing big objects by const reference is the usual default.
C++
#include <algorithm>
#include <iostream>
#include <vector>
void add_bonus(std::vector<int>& scores, int bonus) {
for (int& s : scores) {
s += bonus;
}
}
int sum(const std::vector<int>& scores) {
int total = 0;
for (int s : scores) {
total += s;
}
return total;
}
int main() {
std::vector<int> scores = {82, 91, 76};
add_bonus(scores, 5);
std::cout << scores[0] << " " << scores[1] << " " << scores[2] << "\n";
std::cout << sum(scores) << "\n";
auto [low, high] = std::minmax_element(scores.begin(), scores.end());
std::cout << *low << " " << *high << "\n";
auto copy = scores;
copy[0] = 0;
std::cout << scores[0] << " " << copy[0] << "\n";
auto& alias = scores;
alias[0] = 100;
std::cout << scores[0] << "\n";
}