Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading