我在C++中有這個片段。C++字符串中的「大小」和「容量」之間的區別?
#include <iostream>
#include <string>
int main()
{
string bigNews("I saw Elvis in a UFO. ");
cout << bigNews << endl;
bigNews.insert(0, " thought I ");
cout << bigNews << endl;
cout << "Size = " << bigNews.size() << endl;
cout << "Capacity = "
<< bigNews.capacity() << endl;
bigNews.append("I've been working too hard.");
cout << bigNews << endl;
cout << "Size = " << bigNews.size() << endl;
cout << "Capacity = "
<< bigNews.capacity() << endl;
return 0;
}
而且我得到的輸出如下圖所示:
I saw Elvis in a UFO.
thought I I saw Elvis in a UFO.
Size = 33
Capacity = 44
thought I I saw Elvis in a UFO. I've been working too hard.
Size = 60
Capacity = 88
我可以計算出尺寸增大的原因,但我不能夠做出來怎麼容量增大?
我知道的是容量是字符串緩衝區,我們可以推送,但如何分配空間?
只要滿足該類的複雜性要求,就不能保證以任何特定方式進行分配。 – chris