Reputation: 18219
In C++, the method resize
(of std::vector
), changes the size of the vector (and construct / destroys object if necessary), reserve
allows to eventually increase the capacity of a vector. shrink_to_fit
will reduce the capacity of the vector to match its size. When increasing the vector size (either through resize
, push_back
or insert
), the capacity will be increased if needed (it doubles every time it needs to increase if I am not mistaken).
Do the standards ensure that a vector will never reduce its capacity, unless the function shrink_to_fit
is called? Or is it possible that a vector capacity will vary depending upon what the compiler think being wise to do?
Upvotes: 2
Views: 680
Reputation: 25277
No, the vector's capacity will not be reduced by reserve
or resize
.
If
new_cap
is [not greater thancapacity
] ... no iterators or references are invalidated.
Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators, rather than only the ones that would be invalidated by the equivalent sequence of pop_back() calls.
Upvotes: 4