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 thecapacity(). -
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:
(inspired by “More Exceptional C++”, Item #7)