Why does this code work for arrays but not vectors? When I replace the data type to array, it works. I thought both were mutable. For reference, the program is supposed to return 1 4 10 14 22, or the accumulated value so far for each index.
#include <iostream>
#include <vector>
using namespace std;
void accum(vector<int> v, int len)
{
if (len == 1){
return;
}
accum(v, len-1);
v[len-1] = v[len-2];
}
int main()
{
vector<int> v = {1, 3, 6, 4, 8};
accum(v, 5);
for (int i = 0; i < 5; i ) {
cout << v[i] << " ";
}
return 0;
}
The code works when you implement the function with an array instead of a vector. I have no idea why, or how to make it also work with arrays.
CodePudding user response:
Vectors in C are passed by value into a function unlike arrays.
That means when vectors are passed to a function, C creates a copy of it and then passes. Therefore, when the recursive runs, the original vector is not changed
void accum(vector<int>& v, int len)
and call the function as
vector<int> v;
accum(v, v.size())
CodePudding user response:
you used it -> call by value
solve -> call by reference
before
void accum(vector<int> v, int len) // call by value
after
void accum(vector<int> &v, int len) // call by reference