1

When I have this piece of code:

int push666 (vector<int> vect){

    vect.push_back(666);
}

int main()
{

    vector<int> a;
    a.reserve(1);
    push666(a);

    cout << a[0];

    return 0;
}

The cout will simply print out some garbage value. It seems like functions don't have a lasting effect on the vector. What can I do about it?

  • 3
    `push666` needs to take a `vector&`, not a `vector`. And you need to read a [book](http://stackoverflow.com/q/388242/241631). – Praetorian Nov 20 '15 at 20:29
  • I am going to read one. Your list made it much easier for me, thank you! –  Nov 22 '15 at 10:56

3 Answers3

5

You pass the vector by reference instead of by value.

int push666 (vector<int>& vect){  
                    // ^^^  
    vect.push_back(666);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
3

C++ supports passing by value and by reference.

In your code, the std::vector<int> is passed to the function by value - it is copied and this very copy is modified and std::vector<int>::push_backed.

In order to prevent the copy1, so the function directly operates on a, you need to pass it by reference:

int push666 (vector<int>& vect){
    vect.push_back(666);
}


The other way, the C way (or bad C++ way) is to pass a pointer:

int push666 (vector<int>* vect){
    vect->push_back(666);
}

Note that the pointer is passed by value here.


1 The standard doesn't specify that but a reference is probably implemented with a pointer, so technically some copying is made.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
1

You should pass it by reference:

int push666 (vector<int>& vect){

    vect.push_back(666);
}

or what is less common by pointer:

int push666 (vector<int>* vect){

    vect->push_back(666);
}
push666(&a); // use & to take address of a

both ways allows you to modify arguments passed to functions

marcinj
  • 48,511
  • 9
  • 79
  • 100