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;
}
  
  
  
  
  
  

要求

标头: <string>

命名空间: std

请参见

参考

basic_string Class