次の方法で共有


basic_string::operator[]

文字列に指定したインデックスのある文字への参照を提供します。

const_reference operator[](
   size_type _Off
) const;
reference operator[](
   size_type _Off
);

パラメーター

  • _Off
    参照される要素の位置のインデックス。

戻り値

パラメーター インデックスで指定された位置にある文字列内の文字への参照。

解説

文字列の最初の要素のインデックスにゼロがあり、次の要素に、正の長さ n の文字列に数値 n - 1.インデックスが付けられます。n 番目の要素と同様に、逐次的にインデックスが付けられます。

operator[] は 的なと文字列の要素に対する書き込みアクセスのメンバー関数 場所 よりも高速です。

operator[]、パラメーターとして渡されるインデックスが有効ですが、メンバー関数は 場所 ので、有効ではありません。だけ使用する必要があるかどうかをチェックします。 メンバー関数に渡される 場所 無効なインデックス (より小さいインデックスまたは以上である文字列のサイズに大きなゼロになります) out_of_range クラス の例外をスローします。 無効なインデックスは operator[] に未定義の動作の結果が渡されましたが、文字列の長さと等しいインデックスは const 文字列の有効なインデックスで、このインデックスを渡すと演算子は null 文字を返します。

返される参照はconst の非文字列の文字列の再割り当てまたは変更によって無効になることがあります。

_SECURE_SCL 1 でコンパイルすると、ランタイム エラーは、文字列の境界の外に要素にアクセスしようとすると発生します。詳細については、「チェックを行う反復子」を参照してください。

使用例

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

int main( )
{
   using namespace std;
   string str1 ( "Hello world" ), str2 ( "Goodbye world" );
   const string cstr1 ( "Hello there" ), cstr2 ( "Goodbye now" );
   cout << "The original string str1 is: " << str1 << endl;
   cout << "The original string str2 is: " << str2 << endl;

   // Element access to the non-const strings
   basic_string <char>::reference refStr1 = str1 [6];
   basic_string <char>::reference refStr2 = str2.at ( 3 );

   cout << "The character with an index of 6 in string str1 is: "
        << refStr1 << "." << endl;
   cout << "The character with an index of 3 in string str2 is: "
        << refStr2 << "." << endl;

   // Element access to the const strings
   basic_string <char>::const_reference crefStr1 = cstr1 [ cstr1.length ( ) ];
   basic_string <char>::const_reference crefStr2 = cstr2.at ( 8 );

   if ( crefStr1 == '\0' )
      cout << "The null character is returned as a valid reference."
           << endl;
   else
      cout << "The null character is not returned." << endl;
   cout << "The character with index of 8 in the const string cstr2 is: "
        << crefStr2 << "." << endl;
}

出力

The original string str1 is: Hello world
The original string str2 is: Goodbye world
The character with an index of 6 in string str1 is: w.
The character with an index of 3 in string str2 is: d.
The null character is returned as a valid reference.
The character with index of 8 in the const string cstr2 is: n.

必要条件

ヘッダー: の <文字列>

名前空間: std

参照

関連項目

basic_string クラス