函数原型
reserve
原型:
#include <string> void reserve( size_type size = 0 );
函数reserve()将字符串的容量设置为至少size. 如果size指定的数值要小于当前字符串中的字符数(亦即size < this→size()), 容量将被设置为可以恰好容纳字符的数值. reserve()以线性时间(linear time)运行.
resize
原型:
#include <string> void resize( size_type size, char val = char() );
函数resize()将字符串的尺寸设置为size. 如果val被指定, 则新创建的元素都将被初始化为val. 此函数以线性时间(linear time)运行.
capacity
原型:
#include <string> size_type capacity() const;
函数capacity()返回string预先保留的最大元素数量.
string类型中size()和length()分别返回string中含有的字符个数、string的字符串长度;对于某个string来说,两者的返回值是一样的。
对于如下的代码:
int main() {
//section A
string str;
getline(cin, str);
cout << "size: " << str.size() << endl;
cout << "length: " << str.length() << endl;
cout << "capacity: " << str.capacity() << endl;
//section B
/*str.resize(2);
cout << endl;
cout << str << endl;
cout << "size: " << str.size() << endl;
cout << "length: " << str.length() << endl;
cout << "capacity: " << str.capacity() << endl;*/
//section C
str.reserve(2);
cout << endl;
cout << str << endl;
cout << "size: " << str.size() << endl;
cout << "length: " << str.length() << endl;
cout << "capacity: " << str.capacity() << endl;
}
如果运行section A 和 section B部分代码,结果如图所示:
如果运行section A 和section C部分代码,结果如图所示:
可以看出,resize后将string类型的str的空间变为了resize的数值;而reserve后,如果size指定的数值要小于当前字符串中的字符数(亦即size < this→size()), 容量将被设置为可以恰好容纳字符的数值