capacity()
string类capacity()容器的大小会因编译器的不同而得到的容量大小有所不同;
VS2017中string类首次分配空间为15,溢出之后分配为+16,之后每溢出16就+16,简而言之规律就是:15+16+16+16+;
VC++6.0中string类首次分配空间为31,溢出之后分配为+32,之后每溢出32就+32,简而言之规律就是:31+32+32+32+;
还有测试了多个c++在线编译器、VS code和code blocks的string类首次分配空间均为15,溢出之后分配实际所需空间,简而言之就是15+实际溢出空间大小。【个人实践经验,仅供参考】
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str0("guangdongsheng");
string str1("China.GuangDongSheng");
string str2("Universe.Earth.China.GuangDongSheng");
cout << str0 << endl;
cout << str0.capacity() << endl;
cout << str0.size() << endl;
cout << str0.length() << endl;
cout << str1 << endl;
cout << str1.capacity() << endl;
cout << str1.size() << endl;
cout << str1.length() << endl;
cout << str2.c_str() << endl;
cout << str2.capacity() << endl;
cout << str2.size() << endl;
cout << str2.length() << endl;
return 0;
}
输出结果:
guangdongsheng
15
14
14
China.GuangDongSheng
31
20
20
Universe.Earth.China.GuangDongSheng
47
35
35