Cray
Cray

Reputation: 2454

Does resize() to a smaller size discard the reservation made by earlier reserve()?

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?

Upvotes: 6

Views: 1707

Answers (2)

josephthomas
josephthomas

Reputation: 3276

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

Upvotes: 2

George Skoptsov
George Skoptsov

Reputation: 3951

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

Upvotes: 6

Related Questions