Downsizing a std::Vector: The Swap Trick
To reduce the capacity of a std::vector when the reserved space is no longer required, the "swap trick" recommended by Scott Meyers in his book "Effective STL" can be employed. Here's how it works:
vector<Person> new_persons(size_of_new_vector);
new_persons.swap(persons);
After performing the swap, the original vector, persons, will be "shrunk to fit," meaning it will occupy only the memory necessary for the number of elements it currently holds.
This technique leverages the vector's copy constructor, which allocates memory only for the elements being copied, effectively reducing the excess capacity of the original vector.
The above is the detailed content of How to Shrink a std::vector to its Actual Size: The Swap Trick Explained. For more information, please follow other related articles on the PHP Chinese website!