简体   繁体   中英

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.

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())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM