这个例子展示了两个有趣的事情。首先,200年虽然我们请求的能力,我们实际上有一个容量为207。能力总是保证至少一样大你的要求,但可能更大。然后,我们要求的能力改变以适应字符串。这个请求被忽略,没有改变的能力。
如果你提前知道你将要建造一个大型的字符串通过做大量的字符串操作会增加大小的字符串,字符串可以避免重新分配多次通过立即设置字符串的最后容量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include
<iostream> #include
<string> #include
<cstdlib> // for rand() and srand() #include
<ctime> // for time() using
namespace
std; int
main() { srand ( time (0));
//
seed random number generator string
sString; //
length 0 sString.reserve(64);
//
reserve 64 characters //
Fill string up with random lower case characters for
( int
nCount=0; nCount < 64; ++nCount) sString
+= 'a'
+ rand ()
% 26; cout
<< sString; } |
这个程序的结果将改变每一次,但这里的输出一个执行:
wzpzujwuaokbakgijqdawvzjqlgcipiiuuxhyfkdppxpyycvytvyxwqsbtielxpy
而不必重新分配sString多次,我们设置的能力一次,然后填充字符串。这可以使一个巨大的差异表现在构建大型通过连接字符串。