I know that vectors double in size whenever their capacity()
is exceeded. This operation takes some time which is why vectors are supposed to have amortized constant time for addition of elements with push_back()
.
What I'm wondering is... what happens when a vector shrinks so that its size()
is less than half of the capacity()
.
Do vectors ever relinquish the memory which they use, or is it just gone until the vector is destroyed?
It could be a lot of wasted memory if they don't shrink in size ever, but I've never heard of them having that feature.
No, it is never freed (i.e. capacity is never reduced) until destruction. A common idiom for freeing up some memory is to create a new vector of the correct size, and use that instead:
std::vector<type>(originalVector).swap(originalVector);
(inspired by "More Exceptional C++", Item #7)
If you want to make sure your vector uses as little space as possible, you can say:
std::vector<Foo>(my_vector).swap(my_vector);
You could also call the shrink_to_fit()
member function, but that is just a non-binding request.
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