So if I reserve(100) first, add some elements, and then resize(0) (or any other number smaller than the current size), will the vector reallocate memory to a take less space than 100 elements?
The main difference between vector resize() and vector reserve() is that resize() is used to change the size of vector where reserve() doesn't. reserve() is only used to store at least the number of the specified elements without having to reallocate memory.
Calling resize() with a smaller size has no effect on the capacity of a vector . It will not free memory.
reserve() does not change the size of the vector.
C++ Vector Library - resize() Function 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.
vector<T>::resize(0)
should not cause a reallocation or deletion of allocated memory, and for this reason in most cases is preferable to vector<T>::clear()
.
For more detail see answers to this question: std::vector resize downward
Doing a vector::resize(0)
or to a smaller count rather than current count should not deallocate any memory. However, it may destroy these elements.
For a reference on std::vector::resize
, take a look at std::vector::resize
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