How to downsize std::vector?

Effective STL, by Scott Meyers, Item 17: Use the swap trick to trim excess capacity.

vector<Person>(persons).swap(persons);

After that, persons is "shrunk to fit".

This relies on the fact that vector's copy constructor allocates only as much as memory as needed for the elements being copied.


If you're using C++11, you can use vec.shrink_to_fit(). In VS2010 at least, that does the swap trick for you.