0

I just started learning C++ today so I'm not familiar with whether I'm referencing the original vector or a copy. I'm trying to double the values of all the elements in my vector (go from 1, 2, 3 to 2, 4, 6) but the vector always prints the original values. Any tips are appreciated!

void doubleVector(vector<int> vec) {
    for (int i = 0; i < vec.size(); ++i) {
        vec[i] = vec[i] * 2;
    }
}

int main() {
    vector<int> vect{ 1, 2, 3 };
    doubleVector(vect);
    for (int x : vect) {
        std::cout << x << ' ';
    }
}
xander
  • 87
  • 4
  • 1
    That's a copy. `void doubleVector(vector & vec)` would be a pass by reference. – user4581301 Jan 28 '22 at 21:55
  • Unrelated: you could write `for (int & val:vec) { val *= 2; }`. This lets the compiler figure out all of the iteration logic for you just like the loop in `main`. Note that `val` is a also reference to prevent operating on a copy. – user4581301 Jan 28 '22 at 21:58
  • Unfortunately, though there are probably over a thousand duplicates of this exact problem, the vernacular and titles used to describe the posts makes them near-unhittable when searching for key terms. The short order is, you're passing your vector by value, so only the local vector `vec` is actually changed. It is the same as a non-complex object: `(int x)` and then `x = x+1;` for example; would suffer the same fate. Changing to a reference, `vector &vec` , will deliver the behavior you seek. – WhozCraig Jan 28 '22 at 22:01
  • @OP It doesn't matter if it's a simple `int` or a `std::vector>>`. Variables in C++ are passed by value (a copy is created), unless you specifically state to pass by reference. This is the big difference between languages like Python or Java, and C++. – PaulMcKenzie Jan 28 '22 at 22:02
  • 1
    The fun one is `void func(type * pointer)` what `pointer` points at is passed by a type of reference and can be modified inside `func` with lasting effects but `pointer` itself is passed by value and a copy. If you need to change where `pointer` points in `func`, you need to pass `pointer` by reference: `void func(type * & pointer)` – user4581301 Jan 28 '22 at 22:14
  • Great to see you starting your learning of C++ with `vector` and not `new` and `delete`-ing arrays. Sounds like you're working from some decent learning materials. – user4581301 Jan 28 '22 at 22:16

1 Answers1

0

If you want to change an object, you need to pass it by pointer of by reference.

Here, you pass vector<int> vec to the function doubleVector which will copy your vector instead of passing it.

Remplace that by void doubleVector(vector<int>& vec) and it will work fine.