首先将这段代码分别再VS2019和Linux运行
int main()
{
vector<int>vv;
int pre_capacity = 0;
for (int i = 0; i < 100000; i++)
{
if (pre_capacity != vv.capacity())
{
cout << "capacity change->" << vv.capacity() << endl;
pre_capacity = vv.capacity();
cout << "vv的地址change->" << &vv << endl;
}
vv.push_back(i);
}
return 0;
}
VS2019
Linux
我们发现在Windows下增容是1.5倍,Linux是2倍,这与扩容底层原理有关。
Vector的增长方式是“重新配置,移动数据,释放原空间”。