reserve()和resize()区别:
- reserve是容器预留空间,但在空间内不真正创建元素对象,所以在没有添加新的对象之前,不能引用容器内的元素。
- resize是改变容器大小,且在创建对象。饮茶,调用这个函数之后,就可以引用容器内的对象。
为什么使用reserve()?
vector<int> v;
int num = 0;
int* address = nullptr;
for (int i = 0; i < 10000; i++) {
v.push_back(i);
if (address != &(v[0])) {
num++;
address = &(v[0]);
}
}
cout << "num=" << num << endl;
结果:表示v重新分配24次内存,造成资源浪费。
使用reserve()后:
vector<int> v;
int num = 0;
int* address = nullptr;
v.reserve(10000);//这里!
for (int i = 0; i < 10000; i++) {
v.push_back(i);
if (address != &(v[0])) {
num++;
address = &(v[0]);
}
}
cout << "num=" << num << endl;
结果: