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

来自cppreference.com
< cpp‎ | container‎ | vector

void shrink_to_fit();
(C++11 起)
(C++20 前)
constexpr void shrink_to_fit();
(C++20 起)

请求移除未使用的容量。

它是减少 capacity()size()非强制性请求。请求是否达成依赖于实现。

若发生重分配,则所有迭代器,包含尾后迭代器,和所有到元素的引用都被非法化。若不发生重分配,则没有迭代器或引用被非法化。

参数

(无)

类型要求
-
T 必须满足可移动插入 (MoveInsertable) 的要求。

返回值

(无)

复杂度

至多与容器大小成线性。

注解

T 的移动构造函数以外的操作抛出异常,则无效果。

示例

#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';
}

可能的输出:

Default-constructed capacity is 0
Capacity of a 100-element vector is 100
Capacity after resize(50) is 100
Capacity after shrink_to_fit() is 50
Capacity after clear() is 50
Capacity after shrink_to_fit() is 0
Capacity after adding 300 elements is 512
Capacity after shrink_to_fit() is 300

参阅

返回容纳的元素数
(公开成员函数)
返回当前存储空间能够容纳的元素数
(公开成员函数)