为具有字符串中指定索引的字符提供引用。
const_reference at(
size_type _Off
) const;
reference at(
size_type _Off
);
参数
- _Off
元素的位置的索引将引用。
返回值
对字符串中字符的引用在参数指定的索引位置。
备注
字符串中的第一个元素的索引为零,而且正整数运行以下元素索引,因此长度,n 字符串有数字索引的 第N 个元素 n - 1。
operator[] 成员比提供的读写访问成员函数 at 快访问字符串的元素。
成员 operator[] 不检查作为参数传递的索引是否有效,但成员 at 函数执行,所以应使用,如果无法确定有效性。 无效的索引,该索引为或大于或等于该字符串的大小,传递给成员 at 函数 out_of_range 类 引发异常。 无效的索引传递给 operator[] 导致未定义的行为,但是索引,等于字符串的长度为常量字符串的一个有效的索引,而运算符返回空字符,传递该索引。
返回的引用可能由字符串重新分配或修改非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;
}
Output
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