Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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?


1 Answers

You pass the vector by reference instead of by value.

int push666 (vector<int>& vect){  
                    // ^^^  
    vect.push_back(666);
}
like image 187
R Sahu Avatar answered Dec 22 '25 06:12

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!