Resizing a vector does not destroy the values ββstored in the vector (with the exception of those that exceed the new size during compression, of course), however, a growing vector, beyond its capabilities, copies (or, in C ++ 11, moves) them to a new location, such invalid, and iterators, pointers, or references to these elements.
In your sample program, you do not store iterators, pointers, or references to vector elements during resizing, so you get access to copied values ββif the data was copied during resizing (which is probably, but not completely accurate, the vector can allocate space for more than necessary elements, because with its growth it is often necessary to fulfill the complexity requirements).
You can get the current capacity (the number of elements that you can grow before redistributing) through the capacity
member function. As long as the vector does not go beyond the current capacity, even iterators, pointers, and references to stored objects are safe. In addition, if you want to make sure that iterators, pointers, or references are invalid, and you know in advance the maximum size by which the vector can grow, you can preallocate all the necessary memory using the reserve
member function.
source share