std::vector<T,Allocator>::shrink_to_fit

Requests the removal of unused capacity.

# Declarations

void shrink_to_fit();

(constexpr since C++20)

# Notes

In libstdc++, shrink_to_fit() is not available in C++98 mode.

# Example

#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v;
    std::cout << "Default-constructed capacity is " << v.capacity() << '\n';
    v.resize(100);
    std::cout << "Capacity of a 100-element vector is " << v.capacity() << '\n';
    v.resize(50);
    std::cout << "Capacity after resize(50) is " << v.capacity() << '\n';
    v.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\n';
    v.clear();
    std::cout << "Capacity after clear() is " << v.capacity() << '\n';
    v.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\n';
    for (int i = 1000; i < 1300; ++i)
        v.push_back(i);
    std::cout << "Capacity after adding 300 elements is " << v.capacity() << '\n';
    v.shrink_to_fit();
    std::cout << "Capacity after shrink_to_fit() is " << v.capacity() << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 755C++98std::vector lacked explicit shrink-to-fit operationsprovided
LWG 2033C++98C++111. the complexity requirement was missing (C++98)2. T was not required to be MoveInsertable (C++11)1. added2. required
LWG 2223C++98C++111. references, pointers, and iterators were not invalidated (C++98)2. there was no exception safety guarantee (C++11)1. they may be invalidated2. added

# See also