//预留空间:减少vector在动态扩展容量时的扩展次数
//函数原型:
//reserve(int len); //容器预留len个元素长度,预留位置不初始化,元素不可访问
#include<vector>
#include<iostream>
using namespace std;
void test01() {
vector<int> v;
//预留空间
//这一行是否注释掉,影响着num值大小
v.reserve(100000);
int num = 0;
int* p = NULL;
for (int i = 0; i < 100000; i++) {
//因为vector容器添加数据导致容量增加,不会在结尾拼接,而是开辟一块新的内存空间
//故每次容量增加,首地址都会发生变化
v.push_back(i);
if (p != &v[0]) {
p = &v[0];
num++;
}
}
//开辟新空间次数
cout << "num:" << num << endl;
}
int main() {
test01();
}
c++笔记 STL vector容器_预留空间
最新推荐文章于 2024-01-11 21:28:52 发布