vector的自增长方式:设原vector大小为n,重新分配之后,vector大小变为3n/2,即每次增长的大小为原vector大小的1/2,采用向下取整
代码1,初始大小是1:
- #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;
- }
#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
- 2
- 3
- 4
- 6
- 9
- 13
- 19
- 28
- 42
- 63
- 94
- 141
- 211
- 316
- 474
- 711
- 1066
- 1599
- 2398
- 3597
- 5395
- 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:
- 11
- 16
- 24
- 36
- 54
- 81
- 121
- 181
- 271
- 406
- 609
- 913
- 1369
- 2053
- 3079
- 4618
- 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增长并不是翻倍方式的。