RatkinHHK
RatkinHHK

Reputation: 47

Passing a vector as argument to function

I have a function like this:

void Foo(std::vector<bool> Visited, int actual element);

I actually use this function for a BFS in a Graph, but it goes in an infinite loop. I suspect it always creates a copy of the Visited vector. How do I make it change the vector, which is declared and initialized somewhere in main? And am I right with the whole "makes a copy" theory?

How do I use a pointer to an object, as I think <vector> is an object?

Upvotes: 2

Views: 9698

Answers (2)

flogram_dev
flogram_dev

Reputation: 42888

Pass it by reference:

void Foo(std::vector<bool>& Visited, int actual element); 
                          ^

Now you can modify the original vector passed to Foo.

And am I right with the whole "makes a copy" theory?

Yes. Declaring the parameter with no & or * passes the object by value = as a copy. The same applies to return types etc. (With the exception of move constructors)

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

Use the referenced type

void Foo(std::vector<bool> &Visited, int actual element);

Otherwise the function deals with a copy of the original vector.

Here is a dempnstrative program

#include <iostream>
#include <vector>

void f( std::vector<int> &v )
{
    v.assign( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } );
}

int main() 
{
    std::vector<int> v;

    f( v );

    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;
}    

The program output is

0 1 2 3 4 5 6 7 8 9 

Upvotes: 2

Related Questions