Shrinking the Capacity of an std::vector
When dealing with vectors that are used primarily for reading after they have been populated, it may be beneficial to reduce their capacity.
Current Solutions
Typically, developers resort to creating a new vector with a specified size and copying the elements over. However, this approach introduces an unnecessary copy operation.
C 11 Solution
For C 11 users, the shrink_to_fit() member function provides a convenient solution.
vec.shrink_to_fit();
Implementation Details
As stated in the draft C 11 standard, shrink_to_fit() is a "non-binding request" to reduce capacity to size. This flexibility allows for implementation-specific optimizations. In practice, most implementations will attempt to reduce capacity to the requested size. However, they retain the freedom to optimize based on factors such as system resources or potential future requirements.
The above is the detailed content of How Can I Reduce the Capacity of an std::vector in C ?. For more information, please follow other related articles on the PHP Chinese website!