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?
1 Answer 1
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.
answered Feb 16, 2014 at 12:36
WeaselFox
7,3989 gold badges53 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Orange Fox
Ty for answer. Where can i find information about using this "&" symbol in c++ ?
WhozCraig
@OrangeFox in literally any C++ book in-print since the language was invented. See this list for suggestions
lang-cpp
vector<int>& vjob done.push_backin the first place. Why do you do that?