Home >Backend Development >C++ >How to Shrink a std::vector to its Actual Size: The Swap Trick Explained

How to Shrink a std::vector to its Actual Size: The Swap Trick Explained

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 07:05:03507browse

How to Shrink a std::vector to its Actual Size: The Swap Trick Explained

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:

  1. Create a new vector with the desired capacity:
vector<Person> new_persons(size_of_new_vector);
  1. Swap the contents of the original and new vectors:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn