basic_string::at

Zawiera odwołanie do znaku o określonym indeksie w ciągu.

const_reference at(
    size_type _Off
) const;
reference at(
    size_type _Off
);

Parametry

  • _Off
    Indeks pozycji elementu, który ma się odwoływać.

Wartość zwracana

Odwołanie do znaku ciągu w pozycji określonej przez parametr indeksu.

Uwagi

Pierwszy element w ciągu ma indeks równy zero i następujące elementy są indeksowane kolejno przez dodatnich liczb całkowitych, aby ciąg o długości n ma nth element indeks z numerem n- 1.

Członek operatora [ jest szybsze niż funkcji członka w za dostarczanie odczytu i zapisu do elementów ciąg.

Członek operator[] nie sprawdza, czy indeks przekazywana jako parametr jest prawidłowy, ale funkcji członka w wykonuje i tak należy stosować, jeśli ważność nie jest pewne.Nieprawidłowy indeks, który jest indeks mniejszej od zera lub większa niż lub równa rozmiarowi ciąg, przekazany do funkcji członka w wyrzuca out_of_range klasy wyjątek.Nieprawidłowy indeks przekazany do operator[] skutkuje niezdefiniowane zachowanie, ale indeks równa długość ciągu jest prawidłowym indeksem const ciągi i operator zwraca znak null przekazano tego indeksu.

Zwracane odwołanie może unieważnione przez ciąg przeniesieniom lub modyfikacji dla non -const ciągów.

Przykład

// 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;
}

Dane wyjściowe

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.

Wymagania

Nagłówek: <ciąg>

Przestrzeń nazw: std

Zobacz też

Informacje

basic_string — Klasa