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:
In C++11 we can use the
shrink_to_fit() member function for a similar effect:
shrink_to_fit() member function is a request and doesn't guarantee to reduce capacity.