0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • You're passing by value, you need to pass by reference. – vandench Dec 30 '21 at 17:35
  • There should be a FAQ question about passing by value to make questions like this duplicate of it. This is third question I see just in last 2 days about it. – Slava Dec 30 '21 at 17:59

3 Answers3

4

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) { ... }
nanofarad
  • 40,330
  • 4
  • 86
  • 117
2

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218