std::vector resize downward

Calling resize() with a smaller size has no effect on the capacity of a vector. It will not free memory.

The standard idiom for freeing memory from a vector is to swap() it with an empty temporary vector: std::vector<T>().swap(vec);. If you want to resize downwards you’d need to copy from your original vector into a new local temporary vector and then swap the resulting vector with your original.

Updated: C++11 added a member function shrink_to_fit() for this purpose, it’s a non-binding request to reduce capacity() to size().

Leave a Comment