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.

Leave a Comment