c++vectorpush-back

Vector parameter in a function doesn't seem to actually apply to input?


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();
}

Solution

  • 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.