我是在vs2013下所做的测试,实验结果可能和在vc6.0或者其他编译器上有所不同.
当string的元素个数<=15时,容量恒为15,当新元素增加等导致容量增加时,取原容量的1.5倍和原容量+16的一个倍数作比较,取大值.那么这个倍数怎么取呢?只要原容量一次次的增加16,当数值大于所需新容量时即可.
string容量第一个例子:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "asda";
cout << s.capacity() << endl; //15 :刚开始元素个数≤15时,容量分配为15.
s.reserve(16);
cout << s.capacity() << endl; //31 :16*1.5=24 15+16=31,所以新容量为31.
s.reserve(33);
cout << s.capacity() << endl; //47 :31*1.5=47.5 31+16=47,所以新容量为47.
s.reserve(49);
cout << s.capacity() << endl; //70 :47*1.5=70 47+16=63,所以新容量为70.
s.resize(85);
cout << s.capacity() << endl; //105 :70*1.5=105 70+16=86,所以新容量为105.
s.reserve(111);
cout << s.capacity() << endl; //157 :105*1.5=157.5 105+16=121,所以新容量为157.
s.resize(185);
cout << s.capacity() << endl; //235 :157*1.5=235.5 157+16*2=189,所以新容量为189.
system("pause");
return 0;
}
string容量第二个例子:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "asda";
cout << s.capacity() << endl; //15
s.reserve(16);
cout << s.capacity() << endl; //31 :15*1.5=22.5 15+16=31,所以新容量为31.
s.resize(49);
cout << s.capacity() << endl; //63 :31*1.5=47.5 31+16*2=63.所以新容量为63.
s.reserve(85);
cout << s.capacity() << endl; //95 :63*1.5=94.5 63+16*2=95.所以新容量为95.
s.resize(176);
cout << s.capacity() << endl; //191 :95*1.5=142.5 95+16*6=191.所以新容量为191.
s.reserve(235);
cout << s.capacity() << endl; //286 :191*1.5=286.5 191+16*3=239.所以新容量为286.
system("pause");
return 0;
}
vector的容量变化和string不同,刚开始有多少元素,容量则为多少,然后用原容量的1.5倍和新需求量相比,取大值,但是调用reserve时,则是直接配置成指定容量,且容量不会变小!
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{ //当容量自动增加后的过程是:重新配置,元素移动,释放原空间.非常麻烦.
vector<int> s;
cout << s.capacity() << endl; //0
s.push_back(1);
cout << s.capacity() << endl; //1
s.insert(s.begin(), 6, 1);
cout << s.capacity() << endl; //7 :1*1.5=1.5 1+6=7.所以新容量为7.
s.resize(17);
cout << s.capacity() << endl; //17 :7*1.5=10.5 17.所以新容量为17.
s.resize(26);
cout << s.capacity() << endl; //26 :17*1.5=25.5所以新容量为26.
s.reserve(34);
cout << s.capacity() << endl; //34:
s.resize(50);
cout << s.capacity() << endl; //51:34*1.5=51.5>50所以新容量为51.
system("pause");
return 0;
}