Vector的自增长方式



vector的自增长方式:设原vector大小为n,重新分配之后,vector大小变为3n/2,即每次增长的大小为原vector大小的1/2,采用向下取整


代码1,初始大小是1:

  1. #include <iostream>  
  2. #include <vector>  
  3. #include <list>  
  4. #include <string>  
  5. #include <fstream>  
  6. using namespace std;  
  7.   
  8. int main()  
  9. {  
  10.     vector<string> vec(1) ;  
  11.     ofstream of;  
  12.     of.open("d:/out.txt",ios::out);  
  13.     if(of.bad())  
  14.     {  
  15.         cout<<"can not open file D:\\out.txt"<<endl;  
  16.         return -1;  
  17.     }  
  18.     int lastCap = vec.capacity();  
  19.     of<<lastCap<<endl;  
  20.     while(vec.capacity() < 10000 )  
  21.     {  
  22.         if(vec.capacity() != lastCap)  
  23.         {  
  24.             of<<vec.capacity()<<endl;  
  25.             lastCap = vec.capacity();  
  26.         }  
  27.   
  28.         vec.push_back("AAA");  
  29.     }  
  30.     of.close();  
  31.     return 0;  
  32. }  
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <fstream>
using namespace std;

int main()
{
    vector<string> vec(1) ;
    ofstream of;
    of.open("d:/out.txt",ios::out);
    if(of.bad())
    {
        cout<<"can not open file D:\\out.txt"<<endl;
        return -1;
    }
    int lastCap = vec.capacity();
    of<<lastCap<<endl;
    while(vec.capacity() < 10000 )
    {
        if(vec.capacity() != lastCap)
        {
            of<<vec.capacity()<<endl;
            lastCap = vec.capacity();
        }

        vec.push_back("AAA");
    }
    of.close();
    return 0;
}


输出1:

  1. 1  
  2. 2  
  3. 3  
  4. 4  
  5. 6  
  6. 9  
  7. 13  
  8. 19  
  9. 28  
  10. 42  
  11. 63  
  12. 94  
  13. 141  
  14. 211  
  15. 316  
  16. 474  
  17. 711  
  18. 1066  
  19. 1599  
  20. 2398  
  21. 3597  
  22. 5395  
  23. 8092  
1
2
3
4
6
9
13
19
28
42
63
94
141
211
316
474
711
1066
1599
2398
3597
5395
8092

如果初始大小设为11,那么输出又会是:

输出2:

  1. 11  
  2. 16  
  3. 24  
  4. 36  
  5. 54  
  6. 81  
  7. 121  
  8. 181  
  9. 271  
  10. 406  
  11. 609  
  12. 913  
  13. 1369  
  14. 2053  
  15. 3079  
  16. 4618  
  17. 6927  
11
16
24
36
54
81
121
181
271
406
609
913
1369
2053
3079
4618
6927


以上输出在VS2010 和 mingw g++下面测试,结果均一样, 可见在mingw g++ 下和 VS2010下 vector的capacity增长并不是翻倍方式的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值