Let’s assume I informed you that I desire 5 elements, so size_vector
will be 5.
On the line
vector<int>values(size_vector)
You define an integer vector of size 5 initialized with 0. That is, it would have something like:
values = [0, 0, 0, 0, 0]
Inside your loop you use the method push_back
to change its vector. See documentation:
Add element at the end
Adds a new element at the end of the vector,
after its Current last element. The content of val is copied (or
Moved) to the new element.
This effectively increases the container size by one, which causes an
Automatic reallocation of the allocated Storage space if -and only if-
the new vector size surpasses the Current vector Capacity.
That is, the value will be added to the end of the vector by reallocating the memory needed to store it. If I inform the values from 1 to 5 in the input, its vector would be:
values = [0, 0, 0, 0, 0, 1, 2, 3, 4, 5]
That doesn’t seem to be what you want.
If you just want to change the values in the array you can do:
for(int i = 0; i < size_vector; i++){
cin >> new_value;
values.at(i) = new_value;
}
Since the method at
can return a reference. Once vector
implements the operator []
which can also return a reference, make values[i] = new_value
it is also possible.
I couldn’t even do it
cin >> values[i]
there and remove thenew_value
?– Woss
Yes, I would in the second, I can do
– Maniero