0

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();
}
101123
  • 3
  • 1

2 Answers2

0

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.

Refugnic Eternium
  • 4,089
  • 1
  • 15
  • 24
  • Thank you! I will read up on references & pointers. – 101123 Dec 13 '21 at 07:17
  • Go ahead and do that. Also, if you consider your problem solved, please remember to accept an answer (by clicking the green checkmark below the numbers). This way, others will know, that you no longer require help. – Refugnic Eternium Dec 13 '21 at 07:18
  • Yeah, I clicked that a few minutes ago, but it says I need to wait another 9 minutes. It's now down to 5 minutes, so I will do that ASAP. – 101123 Dec 13 '21 at 07:20
  • Thank you. I really only mentioned it, because you apparently are new. Oh and: Welcome to Stack Overflow. – Refugnic Eternium Dec 13 '21 at 07:21
0

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.

Abhash Kumar Singh
  • 1,157
  • 2
  • 12
  • 22