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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…