请求被忽略

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。能力总是保证至少和你一样大的要求,但可能更大。然后我们要求的能力改变以适应字符串。这个请求被忽略,因为能力并没有改变。

如果你事先知道你要做大量的字符串操作,将添加到字符串的大小构建一个大的字符串,你可以避免字符串分配多次立即设置字符串到它的最终容量:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值