Namespaces
Variants

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

From cppreference.net

void shrink_to_fit ( ) ;
(自 C++20 起为 constexpr)

请求移除未使用的容量。

这是一个非强制性的请求,用于将 capacity() 缩减至 size() 。该请求是否被满足取决于具体实现。

若发生重新分配,所有迭代器(包括 end() 迭代器)及所有元素引用都将失效。若未发生重新分配,则不会使任何迭代器或引用失效。

如果 T 不满足 可移动插入 std:: vector < T, Allocator > 的要求,则行为未定义。

(自 C++11 起)

目录

复杂度

最多与容器大小成线性关系。

异常

若抛出的异常并非来自非 CopyInsertable 类型 T 的移动构造函数,则无任何效果。

(C++11 起)

注释

在 libstdc++ 中, shrink_to_fit() 在 C++98 模式下 不可用

示例

#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v;
    std::cout << "默认构造的容量为 " << v.capacity() << '\n';
    v.resize(100);
    std::cout << "100元素向量的容量为 " << v.capacity() << '\n';
    v.resize(50);
    std::cout << "resize(50)后的容量为 " << v.capacity() << '\n';
    v.shrink_to_fit();
    std::cout << "shrink_to_fit()后的容量为 " << v.capacity() << '\n';
    v.clear();
    std::cout << "clear()后的容量为 " << v.capacity() << '\n';
    v.shrink_to_fit();
    std::cout << "shrink_to_fit()后的容量为 " << v.capacity() << '\n';
    for (int i = 1000; i < 1300; ++i)
        v.push_back(i);
    std::cout << "添加300个元素后的容量为 " << v.capacity() << '\n';
    v.shrink_to_fit();
    std::cout << "shrink_to_fit()后的容量为 " << v.capacity() << '\n';
}

可能的输出:

默认构造的容量为 0
100元素向量的容量为 100
resize(50)后的容量为 100
shrink_to_fit()后的容量为 50
clear()后的容量为 50
shrink_to_fit()后的容量为 0
添加300个元素后的容量为 512
shrink_to_fit()后的容量为 300

缺陷报告

以下行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 755 C++98 std::vector 缺少显式缩容操作 已提供
LWG 2033 C++98
C++11
1. 缺少复杂度要求 (C++98)
2. 未要求 T 满足 MoveInsertable (C++11)
1. 已添加
2. 已要求
LWG 2223 C++98
C++11
1. 未使引用、指针和迭代器失效 (C++98)
2. 没有异常安全保证 (C++11)
1. 可能使其失效
2. 已添加

参见

返回元素数量
(公开成员函数)
返回当前分配存储空间可容纳的元素数量
(公开成员函数)