C++ std::vector Reducing the Capacity of a Vector

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

A std::vector automatically increases its capacity upon insertion as needed, but it never reduces its capacity after element removal.

// Initialize a vector with 100 elements
std::vector<int> v(100);

// The vector's capacity is always at least as large as its size
auto const old_capacity = v.capacity();
// old_capacity >= 100

// Remove half of the elements
v.erase(v.begin() + 50, v.end());  // Reduces the size from 100 to 50 (v.size() == 50),
                                   // but not the capacity (v.capacity() == old_capacity)

To reduce its capacity, we can copy the contents of a vector to a new temporary vector. The new vector will have the minimum capacity that is needed to store all elements of the original vector. If the size reduction of the original vector was significant, then the capacity reduction for the new vector is likely to be significant. We can then swap the original vector with the temporary one to retain its minimized capacity:

std::vector<int>(v).swap(v);
C++11

In C++11 we can use the shrink_to_fit() member function for a similar effect:

v.shrink_to_fit();

Note: The shrink_to_fit() member function is a request and doesn't guarantee to reduce capacity.



Got any C++ Question?