Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function that push_back value to vector in c++

Tags:

c++

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?

like image 459
Orange Fox Avatar asked Aug 01 '26 15:08

Orange Fox


1 Answers

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.

like image 100
WeaselFox Avatar answered Aug 03 '26 03:08

WeaselFox