If I use .reserve(items) on a vector, the vector will allocate enough memory for my guess of the number of items that I'll need.
If I later on use .clear(), will that just clear the vector or save my earlier defined reserve?
thanks.
It is specified that std::vector<T>::clear()
affects the size. It might not affect the capacity. For resetting the capacity, use the swap trick:
std::vector<int> v1; // somehow increase capacity std::vector<int>().swap(v1);
Note: Since this old answer is still getting upvotes (thus people read it), I feel the need to add that C++11 has added std::vector<...>::shrink_to_fit()
, which requests the vector to remove unused capacity.
It will probably not release the reserved memory although I don't think the behaviour is specified in the standard.
EDIT: Ok, just checked and the standard only says that the post-condition is that size() == 0
although I haven't come across a vector
implementation that doesn't hold on to the reserved memory.
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