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!