Remember that elements in an array (and, because a vector uses an array internally, in a vector) are each proper objects. Defining single variables like a
, b
, c
etc. and putting pointers to them in a vector is redundant: Why do you need the storage outside the vector at all? This is all the more true because you pass a reference to the vector to your function.1
(As an aside: What would you do if the vector had 100 elements, or 10000!?)
Instead, you can simply use a vector right away and rely on the fact that each element is already a true int object, like a variable:
#include <iostream>#include <vector>using namespace std;/** * @brief Modify the vector to which the reference refers * @param vecRef */void fillConsecutive(vector <int>& vecRef){ for (int i = 0; i < vecRef.size(); i++) vecRef[i] = i;}int main(){ vector<int> data{ 10, 100, 1'000, 10'000 }; // or fill it any other way // Modify the original vector. fillConsecutive(data); // This line showed the error ;-) for (auto i: data) { cout << i << '\n'; }}
1If, instead, you would copy the entire vector, you would create a second set of elements which are independent of the original ones, and modifying them in the function would not change the originals in the other vector outside of it. In that case you would indeed have to use pointers because the copied addresses in the new vector will still point to the original variables; they contain the same addresses as the elements of the vector outside the function, from which they were copied.
But passing the vector by value (i.e., passing a true, deep copy) would be untypical and is almost surely not what you want. You pass the vector by reference, which is typical, and can readily modify the original object through that reference. Remember: A reference is essentially an alias, another name, for the same object. Nothing is copied when you call the function.