首页 > 代码库 > vector的capacity增长方式

vector的capacity增长方式

     vector的capacity()调用返回vector中最大能够存储的元素个数,也即在下一次需要扩充容量之前能容纳的元素个数。reserve会使容器在必要的时候增长,以便容纳制指定数目的元素。

#include <iostream>#include <vector>using namespace std;int main(){    vector<int> u;    cout << "Initial capaciry of u: " << u.capacity() << "\n";    for(int i = 0; i < 40; ++i)    {        u.push_back(i);        cout<<"size is "<<u.size()<<" ";        cout<<"Now capacity is :" << u.capacity() << "\n";    }    return 0;}

 

运行环境:win7 32bit codeblocks

Initial capaciry of u: 0size is 1 Now capacity is :1size is 2 Now capacity is :2size is 3 Now capacity is :4size is 4 Now capacity is :4size is 5 Now capacity is :8size is 6 Now capacity is :8size is 7 Now capacity is :8size is 8 Now capacity is :8size is 9 Now capacity is :16size is 10 Now capacity is :16size is 11 Now capacity is :16size is 12 Now capacity is :16size is 13 Now capacity is :16size is 14 Now capacity is :16size is 15 Now capacity is :16size is 16 Now capacity is :16size is 17 Now capacity is :32size is 18 Now capacity is :32size is 19 Now capacity is :32size is 20 Now capacity is :32size is 21 Now capacity is :32size is 22 Now capacity is :32size is 23 Now capacity is :32size is 24 Now capacity is :32size is 25 Now capacity is :32size is 26 Now capacity is :32size is 27 Now capacity is :32size is 28 Now capacity is :32size is 29 Now capacity is :32size is 30 Now capacity is :32size is 31 Now capacity is :32size is 32 Now capacity is :32size is 33 Now capacity is :64size is 34 Now capacity is :64size is 35 Now capacity is :64size is 36 Now capacity is :64size is 37 Now capacity is :64size is 38 Now capacity is :64size is 39 Now capacity is :64size is 40 Now capacity is :64