Does clearing a vector affect its capacity?

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();

Leave a Comment