In C++, std::vector::shrink_to_fit() asks the vector to reduce its capacity() closer to its size(), so spare memory can be released.
It is a non-binding request added in C++11: the library may ignore it. Include <vector> to use it.
This is a member of std::vector<T>, a dynamic contiguous array. Elements sit in one block, so v[i] and data() are fast. Growing past capacity() reallocates and can invalidate iterators, references, and pointers. Prefer push_back / pop_back at the end; middle inserts shift elements.
Syntax
Call shrink_to_fit with empty brackets. It takes no arguments.
C++
v.shrink_to_fit();
Call
What it does
v.shrink_to_fit()
Requests that unused memory be released. The elements stay as they are.
A vector has no capacity() function, so you cannot measure the result directly. The call is a hint, not a promise.
Library declarations
C++
void shrink_to_fit(); // since C++11
Parameters
Parameter
Description
None
shrink_to_fit() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
Nothing
shrink_to_fit() returns void. The values and size() do not change.
C++ Examples
Example 1 — Call shrink_to_fit() After Removing Many Elements
Make a big vector small, then ask it to release memory. The values and size are not changed.