basic_string::operator
Poskytuje odkaz na znak se zadaným indexem v řetězci.
const_reference operator[](
size_type _Off
) const;
reference operator[](
size_type _Off
);
Parametry
- _Off
Index umístění prvku, na kterou chcete odkázat.
Vrácená hodnota
Odkaz na znak řetězec určený index parametr pozice.
Poznámky
První prvek řetězce má index 0 a tyto prvky jsou postupně indexována podle kladných celých čísel, aby řetězec s délkou n má nprvek th index číslo n - 1.
**operator[]**je rychlejší než členskou funkci na umožňující čtení a zápis na prvky řetězce.
**operator[]**nekontroluje, zda index předaný jako parametr je platný, ale členskou funkci na se a tak je třeba použít platnost není určitá.Neplatný index (index nižší hodnotu nula nebo větší než nebo rovna velikosti řetězce) členskou funkci byl předán na vyvolá out_of_range třídy výjimku.Byl předán neplatný index operator[] výsledky nedefinované chování, ale indexu rovna délce řetězce je platný index argument řetězce a vrátí znak null při předání tohoto indexu operátor.
Odkaz vrátí pravděpodobně zrušena přerozdělení řetězec nebo změn non -b řetězce.
Při kompilaci s _SECURE_SCL 1, dojde k chybě za běhu při pokusu o přístup k prvku mimo hranice řetězec. Další informace naleznete v tématu Checked – iterátory.
Příklad
// 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;
}
Výsledek
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.
Požadavky
Hlavička: <string>
Obor názvů: std