Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 527
Cray Avatar asked Apr 13 '12 00:04

Cray


People also ask

How does the vector member function resize () differ from reserve ()?

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.

Does resize change capacity?

Calling resize() with a smaller size has no effect on the capacity of a vector . It will not free memory.

Does Reserve change vector size?

reserve() does not change the size of the vector.

How does resize work in C++?

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.


2 Answers

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

like image 150
George Skoptsov Avatar answered Sep 20 '22 03:09

George Skoptsov


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

like image 42
josephthomas Avatar answered Sep 21 '22 03:09

josephthomas