Home > Software engineering >  vector as an argument for recursive function in c
vector as an argument for recursive function in c

Time:12-31

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.

CodePudding user response:

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) { ... }

CodePudding user response:

If you want to modify a vector that was declared outside the scope of your function you should pass it by reference

void function(vector<int>& tab, int n)

Otherwise each call to function will create a function-local copy of tab and only mutate that copy, not the original external vector.

CodePudding user response:

Either you need to declare the first parameter as having the referenced type std::vector<int> & like

void function( std::vector<int> &tab, int n);

Or you should redefine the function such a way that it will return a vector.

Here is a demonstration program.

#include <iostream>
#include <vector>

std::vector<int> function( int n )
{
    std::vector<int> v;

    return n > 0 ? v = function( n - 1 ), v.push_back( n ), v : v;
}

int main()
{
    auto v = function( 10 );

    for (auto &item : v)
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';
}

The program output is

1 2 3 4 5 6 7 8 9 10
  • Related