C++ Vector 库 - shrink_to_fit() 函数
描述
C++ 函数 std::vector::shrink_to_fit() 请求容器减小其容量以适应其大小。
声明
以下是 std::vector::shrink_to_fit() 函数形式 std::vector 头的声明。
C++98
void shrink_to_fit();
参数
None
返回值
None
示例
以下示例显示了 std::vector::shrink_to_fit() 函数的用法。
#include <iostream>
#include <vector>
using namespace std;
int main(void) {
vector<int> v(128);
cout << "Initial capacity = " << v.capacity() << endl;
v.resize(25);
cout << "Capacity after resize = " << v.capacity() << endl;
v.shrink_to_fit();
cout << "Capacity after shrink_to_fit = " << v.capacity() << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Initial capacity = 128 Capacity after resize = 128 Capacity after shrink_to_fit = 25

