Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does clearing a vector affect its capacity?

I instantiate an std::vector foo(1000).

foo.size() is now 1000 and foo.capacity() is also 1000.

If I clear the vector with foo.clear(), the size() is now 0, but what is the capacity()? Does the standard say anything about that?

like image 512
Alan Turing Avatar asked Jul 30 '11 11:07

Alan Turing


People also ask

Does vector clear reduce capacity?

Starting with C++11, we can call the vector::shrink_to_fit function after clear() , which reduces the vector's capacity to fir the size. It works by “requesting” a reallocation on the vector.

Does vector erase change capacity?

No. That's implied by the fact that iterators, pointers and references prior to the point of erase remain valid. Reducing the capacity would require a reallocation.

What happens when you clear a vector?

clear() removes all the elements from a vector container, thus making its size 0. All the elements of the vector are removed using clear() function.

How do you reduce the capacity of a vector?

C++ std::vector Reducing the Capacity of a Vector In C++11 we can use the shrink_to_fit() member function for a similar effect: v. shrink_to_fit();


2 Answers

No, it doesn't. The capacity of a vector never decreases. That isn't mandated by the standard but it's so both in standard library implementations of VC++ and g++. In order to set the capacity just enough to fit the size, use the famous swap trick

vector<T>().swap(foo); 

In C++11 standard, you can do it more explicitly:

foo.shrink_to_fit(); 
like image 172
Armen Tsirunyan Avatar answered Oct 01 '22 15:10

Armen Tsirunyan


To clear a vector and consume as little capacity as possible, use the swap trick:

std::vector<T>().swap(foo); 

This creates an empty vector, swaps its internals with foo, and then destroys the temporary vector, getting rid of the elements that once belonged to foo and leaving foo as if it was freshly created.

like image 31
fredoverflow Avatar answered Oct 01 '22 16:10

fredoverflow