basic_string::reserve

将字符串的容量设置为一个不小于指定数字的数字。

void reserve(
    size_type _Count = 0
);

参数

  • _Count
    内存是保留的字符数。

备注

具有足够容量重要的,因为重新分配是一个很耗时的过程无效引用字符串中字符的所有引用、指针和迭代器。

容量的概念类型字符串的对象与矢量对象的类型。 与矢量成员函数时,reserve 可能调用对象的容量。 请求不约束力,可能或可能不发生。 因为参数的默认值为零,调用 reserve 是一种无约束力请求时字符串的能力以适应当前字符数的字符串中 容量在字符下的当前数目不缩小。

调用 reserve。唯一可能的方式构建字符串的容量。 但是,如上所述,此请求不约束力,可能不发生。

示例

// basic_string_reserve.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( ) 
{
   using namespace std;
   string str1 ("Hello world");
   cout << "The original string str1 is: " << str1 << endl;

   basic_string <char>::size_type sizeStr1, sizerStr1;
   sizeStr1 = str1.size ( );
   basic_string <char>::size_type capStr1, caprStr1;
   capStr1 = str1.capacity ( );

   // Compare size & capacity of the original string
   cout << "The current size of original string str1 is: " 
        << sizeStr1 << "." << endl;
   cout << "The capacity of original string str1 is: "
        << capStr1 << "." << endl << endl;

   // Compare size & capacity of the string
   // with added capacity
   str1.reserve ( 40 );
   sizerStr1 = str1.size ( );
   caprStr1 = str1.capacity ( );

   cout << "The string str1with augmented capacity is: "
        << str1 << endl;
   cout << "The current size of string str1 is: " 
        << sizerStr1 << "." << endl;
   cout << "The new capacity of string str1 is: "
        << caprStr1 << "." << endl << endl;

   // Compare size & capacity of the string
   // with downsized capacity
   str1.reserve ( );
   basic_string <char>::size_type sizedStr1;
   basic_string <char>::size_type capdStr1;
   sizedStr1 = str1.size ( );
   capdStr1 = str1.capacity ( );

   cout << "The string str1 with downsized capacity is: "
        << str1 << endl;
   cout << "The current size of string str1 is: " 
        << sizedStr1 << "." << endl;
   cout << "The reduced capacity of string str1 is: "
        << capdStr1 << "." << endl << endl;
}
  

要求

标头:< 字符串>

命名空间: std

请参见

参考

basic_string 类