vector::shrink_to_fit() 是 C++ STL 中的内置函数,它减少容器的容量以适应其大小并销毁超出容量的所有元素。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v(10);
for (int i = 0; i < 10; i++)
v[i] = i;
cout << "Vector size initially: " << v.size();
cout << "\nVector elements are: ";
for (int i = 0; i < 10; i++)
cout << v[i] << " ";
v.resize(5);//size置为5,capacity不变
cout << "\n\nVector size after resize(5): "
<< v.size();
cout << "\nVector elements after resize(5) are: ";
for (int i = 0; i < 10; i++)
cout << v[i] << " "; //输出后五个数是之前初始化过的数
v.shrink_to_fit();//capacity置为size大小5
cout << "\n\nVector size after shrink_to_fit(): "
<< v.size();
cout << "\nVector elements after shrink_to_fit() are: ";
for (int i = 0; i < 10; i++)
cout << v[i] << " "; //输出后五个数是不可预料的大小,因为已经销毁
return 0;
}
运行结果:
Vector size initially: 10
Vector elements are: 0 1 2 3 4 5 6 7 8 9
Vector size after resize(5): 5
Vector elements after resize(5) are: 0 1 2 3 4 5 6 7 8 9
Vector size after shrink_to_fit(): 5
Vector elements after shrink_to_fit() are: 0 1 2 3 4 -1 -1755884051 134230871 0 2
Process returned 0 (0x0) execution time : 0.033 s
Press any key to continue.
IDE:Code::Blocks
编译器:g++(-std=c++20)