首页 > 技术文章 > vector容器预留空间(8)

huanian 2020-07-10 13:21 原文

功能描述:

  • 减少vector在动态扩展容量时的扩展次数

函数原型:

reserve(int len);  //容器预留len个元素长度,预留位置不初始化,元素不可访问

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 void test_01()
 6 {
 7     vector<int> v;
 8 
 9     //预留空间
10     v.reserve(100000);
11 
12     int num = 0;
13     int* p = NULL;
14     for (int i = 0; i < 100000; i++) {
15         v.push_back(i);
16         if (p != &v[0]) {
17             p = &v[0];
18             num++;
19         }
20     }
21 
22     cout << "num:" << num << endl;
23 }
24 
25 int main(void)
26 {
27     test_01();
28 
29     system("pause");
30     return 0;
31 
32 }

 

推荐阅读