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?

asked Feb 16, 2014 at 12:35
4
  • 3
    vector<int>& v job done. Commented Feb 16, 2014 at 12:36
  • 1
    "Pass by value" vs "pass by reference", look it up. Commented Feb 16, 2014 at 12:36
  • Your mistake is trying to wrap push_back in the first place. Why do you do that? Commented Feb 16, 2014 at 12:58
  • @jrok I do not understand your question :'( Commented Feb 16, 2014 at 13:08

1 Answer 1

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.

answered Feb 16, 2014 at 12:36
Sign up to request clarification or add additional context in comments.

2 Comments

Ty for answer. Where can i find information about using this "&" symbol in c++ ?
@OrangeFox in literally any C++ book in-print since the language was invented. See this list for suggestions

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.