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
Release: 2024-10-26 07:05:03
Original
501 people have browsed it

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);
Copy after login
  1. Swap the contents of the original and new vectors:
new_persons.swap(persons);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template