basic_string::at
Poskytuje odkaz na znak se zadaným indexem v řetězci.
const_reference at(
size_type _Off
) const;
reference at(
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 tak, aby řetězec s délkou n má nprvek th index číslo n- 1.
Člen operátoru [ je rychlejší než členskou funkci na umožňující čtení a zápis na prvky řetězce.
Člen operator[] nekontroluje, zda index předaný jako parametr je platný, ale členskou funkci na neobsahuje a tak je užitečný v případě, že platnost není určitá.Neplatný index je index menší nula nebo větší než nebo rovna velikosti řetězec předán do členské funkce na vyvolá out_of_range třídy výjimku.Byl předán neplatný index operator[] má za následek nedefinovaný chování, ale indexu rovna délce řetězce je platný index argument řetězce a vrátí operátor null znak při předání tohoto indexu.
Odkaz vrátí pravděpodobně zrušena přerozdělení řetězec nebo změn non -b řetězce.
Příklad
// 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;
}
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 8 in the const string cstr2 is: n.
Požadavky
Hlavička: <string>
Obor názvů: std