2

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?

RatkinHHK
  • 47
  • 1
  • 3
  • Yes it passes a copy, you could change the signature to `void Foo(std::vector& Visited, int actual element);` to be able to modify the vector within the function. https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value As far as your infinite loop, we cannot help you without seeing the code. – Cory Kramer Jun 19 '15 at 14:54

2 Answers2

4

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)

Russell Greene
  • 2,141
  • 17
  • 29
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
2

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