All lessons
LESSON 31/53Algorithm Foundations
Passing Arrays to Functions
GOALHand a vector to a function without copying it, and keep the changes.
By default a vector handed to a function is COPIED. Changes to that copy do not survive, and on a big vector the copying itself is slow. An & means the function works on the real one instead.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
#include <vector>
using namespace std;
void addOne(vector<int>& v) {
for (int& x : v) {
x = x + 1;
}
}
int sum(const vector<int>& v) {
int total = 0;
for (int x : v) {
total = total + x;
}
return total;
}
int main() {
vector<int> nums = {1, 2, 3};
addOne(nums);
cout << nums[0] << " " << nums[1] << " " << nums[2] << endl;
cout << sum(nums) << endl;
return 0;
}> what you see
2 3 4 9
//LINE BY LINE
Watch it run
Inside main there is one vector, nums = {1, 2, 3}.
A copy, or the original?
C++ gives you three choices. Which one you want depends on whether you are reading or changing.
| Written as | Meaning |
|---|---|
vector<int> v | Хуулбар. Удаан, өөрчлөлт үлдэхгүй / A copy. Slow, changes are lost |
vector<int>& v | Эх нь. Өөрчилж болно / The original. You may change it |
const vector<int>& v | Эх нь, гэхдээ өөрчлөхгүй / The original, but read-only |
If you are only reading, use const& in C++. It is fast and it stops you changing anything by accident.