Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a call to std::vector::clear() set std::vector::capacity() to zero?

Tags:

c++

stl

vector

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.

like image 851
monkeyking Avatar asked Apr 13 '10 09:04

monkeyking


2 Answers

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.

like image 117
sbi Avatar answered Sep 18 '22 13:09

sbi


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.

like image 26
Andreas Brinck Avatar answered Sep 20 '22 13:09

Andreas Brinck