vector as an argument for recursive function in c++

Advertisements

I want to have function like one in the title, but when I declare it like this,

void function(vector<int> tab, int n)
{
    if(n > 0)
    {
        tab.push_back(n);
        function(tab, n - 1);
    }
}

it isn’t working, because tab is still blank.

>Solution :

You’re taking tab by value – each recursive call will operate on a new copy of tab.

You’ll want to pass tab by reference:

void function(std::vector<int>& tab, int n) { ... }

Leave a ReplyCancel reply