您好,登錄后才能下訂單哦!
我是在vs2013下所做的測試,實驗結(jié)果可能和在vc6.0或者其他編譯器上有所不同.
當string的元素個數(shù)<=15時,容量恒為15,當新元素增加等導(dǎo)致容量增加時,取原容量的1.5倍和原容量+16的一個倍數(shù)作比較,取大值.那么這個倍數(shù)怎么取呢?只要原容量一次次的增加16,當數(shù)值大于所需新容量時即可.
string容量第一個例子:
#include <iostream>#include <string>using namespace std;int main() { string s = "asda"; cout << s.capacity() << endl; //15 :剛開始元素個數(shù)≤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; }123456789101112131415161718192021222324
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; }12345678910111213141516171819202122
vector的容量變化和string不同,剛開始有多少元素,容量則為多少,然后用原容量的1.5倍和新需求量相比,取大值,但是調(diào)用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; }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。