basic_string::reserve

文字列のキャパシティを少なくとも指定した数に設定します。

void reserve(
    size_type _Count = 0
);

パラメーター

  • _Count
    メモリを予約する文字数。

解説

十分な容量がある再割り当てが時間のかかるプロセスでは、文字列内の文字を表すすべての参照、ポインターと反復子を無効にするために配置することもできます。

String 型のオブジェクトの容量の概念は型のベクター オブジェクトの場合と同じです。 ベクターとは異なりオブジェクトの容量を縮小する場合、メンバー関数 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 クラス