STL中的vector扩容原理
- 新增元素:vector通过一个连续的数组存放元素,如该数组已经存满,需要重新分配一块内存,将原来的数据拷贝到新的内存中,释放之前的内存,然后再插入新的元素;
- vector的对象被构建的时候,它的capacity是0,当push_back或insert第一个元素后,其capacity变为1;
- 在对vector进行删除元素时,其capacity是不会发生变化的;
- Linux下GCC的扩容方式是以2倍扩容的;
代码事例
#include<iostream>
#include<vector>
using namespace std;
int main(int argc, char** argv)
{
vector<int> datas;
cout << "vector datas capacoity: " << datas.capacity() << endl;
for(int i = 0; i < 10; i++){
datas.push_back(i);
cout << "vector datas size: " << datas.size() << endl;
cout << "vector datas capacity: " << datas.capacity() << endl;
}
//移除3个元素
datas.erase(datas.begin()+2, datas.begin()+5);
cout << "after erase, vector datas size: " << datas.size() << endl;
cout << "after erase, vector datas capacity: " << datas.capacity() << endl;
return 0;
}
//输出结果
vector datas capacoity: 0
vector datas size: 1
vector datas capacity: 1
vector datas size: 2
vector datas capacity: 2
vector datas size: 3
vector datas capacity: 4
vector datas size: 4
vector datas capacity: 4
vector datas size: 5
vector datas capacity: 8
vector datas size: 6
vector datas capacity: 8
vector datas size: 7
vector datas capacity: 8
vector datas size: 8
vector datas capacity: 8
vector datas size: 9
vector datas capacity: 16
vector datas size: 10
vector datas capacity: 16
//发现当vector中的数据删除是不会影像其capacity的
after erase, vector datas size: 7
after erase, vector datas capacity: 16
知乎上有一个关于C++ STL的内存扩容:
C++ STL中vector内存用尽后,为啥每次是两倍的增长,而不是3倍或其他数值?