std::vector shrink_to_fit() 方法
- 自 C++20 起
- 自 C++11 起
// Non const version only
constexpr void shrink_to_fit();
// Non const version only
void shrink_to_fit();
请求移除未使用的容量。这是一个非强制性请求,旨在将capacity()
减少到size()
。请求是否被满足取决于实现。
失效
如果发生重新分配,所有迭代器(包括past-the-end 迭代器)以及所有对元素的引用都将失效。
如果未发生重新分配,则没有迭代器或引用失效。
参数
(无)
类型要求
T
(容器的元素类型)必须满足MoveInsertable
的要求。
返回值
(无)
复杂度
最多与容器大小线性相关 - O(size())。
异常
如果抛出的异常不是由 T
的移动构造函数引起的,则没有副作用(强异常保证)。
示例
Main.cpp
#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