Home >Backend Development >C++ >How to Reduce the Capacity of a `std::vector`?

How to Reduce the Capacity of a `std::vector`?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 03:07:30727browse

 How to Reduce the Capacity of a `std::vector`?

Resizing std::vector: Trimming Excess Capacity

Question: How can I downsize a std::vector to reclaim unused space and reduce capacity?

Answer: To shrink a std::vector to its current size, you can utilize the "swap trick" recommended in Effective STL by Scott Meyers (Item 17). Here's how it works:

1. Create a Temporary Vector:

Create a temporary std::vector with the same data type as the original vector.

<code class="cpp">vector<Person> temp(persons);  // Assuming 'persons' is the original vector</code>

2. Swap the Vectors:

Swap the original vector with the temporary vector using the swap() function.

<code class="cpp">persons.swap(temp);</code>

Explanation:

The std::vector copy constructor allocates memory only for the required number of elements being copied. By swapping the vectors, you essentially create a new vector that fits the current size of the original vector. The original vector then receives the newly allocated size from the temporary vector, effectively trimming the excess capacity.

This approach is efficient and does not involve copying individual elements. It relies on the swap operation, which is a constant-time operation.

The above is the detailed content of How to Reduce the Capacity of a `std::vector`?. 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