Vector的自增长方式

来源:互联网 发布:h5场景源码 编辑:程序博客网 时间:2024/06/01 07:38


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


代码1,初始大小是1:

[cpp] view plaincopyprint?
  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. }  


输出1:

[html] view plaincopyprint?
  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  

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

输出2:

[html] view plaincopyprint?
  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  


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

0 0
原创粉丝点击