basic_string::at
文字列に指定したインデックスのある文字への参照を提供します。
const_reference at(
size_type _Off
) const;
reference at(
size_type _Off
);
パラメーター
- _Off
参照される要素の位置のインデックス。
戻り値
パラメーター インデックスで指定された位置にある文字列内の文字への参照。
解説
文字列の最初の要素のインデックスにゼロがあり、次の要素に、正の長さ n の文字列に数値 – n 1.インデックスが付けられます。n 番目の要素と同様に、逐次的にインデックスが付けられます。
メンバー []演算子 は的なと文字列の要素に対する書き込みアクセスのメンバー関数 場所 よりも高速です。
有効性を確実にあるパラメーターとして渡されるインデックスが有効ですが、メンバー関数が 場所 ため、使用するかどうかを operator[] メンバーはチェックされません。 低いインデックスのメンバー関数 場所 に渡される無効なインデックス、または以上である文字列のサイズに大きなゼロになる out_of_range クラス の例外をスローします。 operator[] に渡される無効なインデックス、未定義の動作が発生しますが、文字列の長さと等しいインデックスは const 文字列の有効なインデックスで、このインデックスを渡すと演算子は null 文字を返します。
返される参照はconst の非文字列の文字列の再割り当てまたは変更によって無効になることがあります。
使用例
// basic_string_at.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 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 8 in the const string cstr2 is: n.
必要条件
ヘッダー: の <文字列>
名前空間: std