Search code examples
c++recursionvectorstdvector

recursive function working for arrays but not vectors c++


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.


Solution

  • 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