'Changing values of elements in a vector using a function [duplicate]

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 << ' ';
    }
}


Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1