user5508287
user5508287

Reputation:

How can I make my vector update when passed in a function?

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?

Upvotes: 1

Views: 4970

Answers (3)

cadaniluk
cadaniluk

Reputation: 15229

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.

Upvotes: 3

marcinj
marcinj

Reputation: 49986

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

Upvotes: 1

R Sahu
R Sahu

Reputation: 206607

You pass the vector by reference instead of by value.

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

Upvotes: 5

Related Questions