Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

vector as an argument for recursive function in c++

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading