Possible Duplicate:
std::vector resize downward
If I resize()
an std::vector
to some size smaller than its current size, is it possible that the vector will ever allocate new memory?
This is important to me for performance reasons.
The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.
Calling resize() with a smaller size has no effect on the capacity of a vector . It will not free memory.
vector::resizeResizes the container to contain count elements. If the current size is greater than count, the container is reduced to its first count elements.
Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. The function alters the container's content in actual by inserting or deleting the elements from it.
No, resize
ing to a smaller size will never reallocate.
In case the container shrinks, all iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before the call.
(From here)
Given that, we can be sure that a reallocation cannot have happened.
resize()
when reducing only changes the logical size. Others have already answered this, so I am adding nothing here. The purpose of this is to optimise for speed, as it does not need to reallocate or move any data.
However when you want to optimise for memory usage, C++11 has introduced a further function shrink_to_fit()
that you may call after your resize()
(or even at any other time) which will actually ensure you don't pay for any memory you don't want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With