vector对象是如何增长的

C++的vector容器相当于提供了长度可变的数组。但是这个“数组”的长度是如何增长的呢?

 

详见C++ Primer(第五版),9.4节。

 

写了一个程序来测试

 1 /* vector对象是如何增长的
 2  * gcc version 4.8.1
 3  */
 4 
 5 #include <iostream>
 6 #include <vector>
 7 
 8 using namespace std;
 9 
10 void printSizeCapacity(vector<int>& ivec)
11 {
12     cout << "size: " << ivec.size() << "\t capacity: " << ivec.capacity() << endl;
13 }
14 
15 int main()
16 {
17     vector<int> ivec;
18 
19     cout << "\nadd 20 elements step by step" << endl;
20     for (int i = 0; i < 20; i++) {
21         printSizeCapacity(ivec);
22         ivec.push_back(0);
23     }
24 
25     cout << "\ncall reserve() to make the vector grow to 50 elements" << endl;
26     ivec.reserve(50);
27     while (ivec.size() != ivec.capacity()) {
28         ivec.push_back(0);
29     }
30     printSizeCapacity(ivec);
31 
32     cout << "\nadd 1 element" << endl;
33     ivec.push_back(0);
34     printSizeCapacity(ivec);
35 
36     cout << "\ncall shrink_to_fit()" << endl;
37     ivec.shrink_to_fit();
38     printSizeCapacity(ivec);
39 
40     return 0;
41 }

 

运行结果:

 

posted @ 2015-03-10 17:29  nipan  阅读(470)  评论(0编辑  收藏  举报