Home > Back-end >  Vector parameter in a function doesn't seem to actually apply to input?
Vector parameter in a function doesn't seem to actually apply to input?

Time:12-14

I have a vector variable named intVec, and I have a function named pushBack, that accepts a vector of type integer just like intVec, but when I actually pass that vector into the function in order to push_back the x parameter, nothing seems to happen.

Output expected from intVec.size() is 1

Output given from intVec.size() is 0

I'm genuinely confused as to what I'm doing incorrectly here.

Perhaps I'm missing something extremely obvious.

#include <vector>

std::vector<int> intVec;

void pushBack(int x, std::vector<int> vec) {
    vec.push_back(x);
}

int main() {
    pushBack(10, intVec);
    std::cout << intVec.size();
}

CodePudding user response:

That is because you pass the vector by value instead of by reference (or pointer).

This means, that when you call the function, the vector you call 'push_back' on is actually an independent copy of the original vector, which get deallocated upon leaving the function.

Try this header instead:

void pushBack(int x, std::vector<int> &vec) {
    vec.push_back(x);
}

The & tells the compiler to pass by reference, meaning that whatever you do to vec, you also do to the vector you originally passed.

CodePudding user response:

Write pushBack as below:

void pushBack(int x, std::vector<int>& vec) {
    vec.push_back(x);
}

The only difference is that here vec is being passed by reference. In your code it is being passed by value.

  • Related