1
2
3
string sString("0123456789abcde");
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
这个程序的输出:
长度:15
能力:15
(结果可能取决于编译器有所不同)。
让我们添加一个字符的字符串,看容量的变化:
1
2
3
4
5
6
7
8
string sString("0123456789abcde");
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
// Now add a new character
sString += "f";
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
This produces the result:
Length: 15
Capacity: 15
Length: 16
Capacity: 31
1
2
3
4
5
6
7
8
9
10
11
string sString("01234567");
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
sString.reserve(200);
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
sString.reserve();
cout << "Length: " << sString.length() << endl;
cout << "Capacity: " << sString.capacity() << endl;
这个例子显示了两个有趣的东西。首先,虽然我们要求200的能力,我们实际上有一个容量207。能力总是保证至少和你一样大的要求,但可能更大。然后我们要求的能力改变以适应字符串。这个请求被忽略,因为能力并没有改变。
如果你事先知道你要做大量的字符串操作,将添加到字符串的大小构建一个大的字符串,你可以避免字符串分配多次立即设置字符串到它的最终容量: