I am newbie in c++. I wanna create function that push_back value to vector.
#include <vector>
#include <iostream>
using namespace std;
void pushVector ( vector <int> v, int value){
v.push_back(value);
}
int main(){
vector <int> intVector;
pushVector (intVector, 17);
cout << intVector.empty(); // 1
}
As you see, my function don't push_back value in vector. Where is my mistake?
you need to pass the vector to the function by reference. The way you wrote the function, it makes a copy of the vector inside its body, and the vector remains unchanged outside of the function.
#include <vector>
#include <iostream>
void pushVector ( vector <int>& v, int value){
v.push_back(value);
}
int main(){
vector <int> intVector;
pushVector (intVector, 17);
cout << intVector.empty() // 1
}
here is a concise explanation of the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With