Reducing the capacity of a vector

suggest change

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);

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::vector:
* Reducing the capacity of a vector

Table Of Contents
8 Arrays
11 Loops
23 std::vector
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype