tags:

views:

243

answers:

5

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.

A: 

It will not affect the underlying buffer size. Which is why you have to use tricks like this to actually get rid of the buffer or make it smaller.

sharptooth
+2  A: 

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.

Andreas Brinck
+1 for checking the standard and "probably" (I'd normally expect the memory to remain). On an embedded system I worked with I actually HAVE come across an implementation that releases the memory on a clear.
Mark B
+1  A: 

No it won't. Try it out by calling vector::capacity().

Further evidence of this is the appearance of shrink_to_fit. The standard's working draft mentions:

Remarks: shrink_to_fit is a non-binding request to reduce capacity() to size(). [ Note: The request is non-binding to allow latitude for implementation-specific optimizations. —end note ]

JRL
+1  A: 

No, it won't set reserve() to 0. Calling clear() calls the destructors of each element and removes them from the vector, leaving the container with size of 0, but the capacity remains unchanged.

jasonline
+11  A: 

std::vector<T>::clear() only affects the size, not the capacity. For resetting the capacity, use the swap trick:

    std::vector<int> v1;

    // somehow increase capacity

    std::vector<int>().swap(v1);
sbi
It's so well-known you can even find it here: http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Clear-and-minimize not the similar "Shrink to fit" for reducing the capacity of the vector to the actual number of elements (when there are some).
Matthieu M.