basic_string::operator[]

为具有字符串中指定索引的字符提供引用。

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

参数

  • _Off
    元素的位置的索引将引用。

返回值

对字符串中字符的引用在参数指定的索引位置。

备注

字符串中的第一个元素的索引为零,并且,正整数运行以下元素索引,因此长度,n 字符串有数字索引的 N 个元素 n - 1。

与提供operator[] 的读写访问成员函数 快速对字符串的元素。

operator[] 不检查作为参数传递的索引是否有效,但成员 at 函数执行,所以有效性应在不确定。 无效的索引 (索引为或大于或等于该字符串的大小) 传递给成员 at 函数 out_of_range 类 引发异常。 无效的索引传递给 operator[]。行为未定义的结果,但是索引,等于字符串的长度为常量字符串的一个有效的索引,而运算符返回空字符,传递该索引。

返回的引用可能由字符串重新分配或修改非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;
}

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 of 8 in the const string cstr2 is: n.

要求

标头:< 字符串>

命名空间: std

请参见

参考

basic_string 类