3

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?

Orange Fox
  • 147
  • 7

1 Answers1

4

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.

Community
  • 1
  • 1
WeaselFox
  • 7,220
  • 8
  • 44
  • 75
  • Ty for answer. Where can i find information about using this "&" symbol in c++ ? – Orange Fox Feb 16 '14 at 12:41
  • 2
    @OrangeFox in literally any C++ book in-print since the language was invented. [See this list for suggestions](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – WhozCraig Feb 16 '14 at 12:44