最終更新日時(UTC):
が更新

履歴 編集

function
<string>

std::basic_string::operator[]

const_reference operator[](size_type pos) const;           // (1) C++03
constexpr const_reference operator[](size_type pos) const; // (1) C++20

reference operator[](size_type pos);                       // (2) C++03
constexpr reference operator[](size_type pos);             // (2) C++20

概要

pos 番目の要素への参照を取得する。

要件

pos <= size()

戻り値

  • C++03

    • pos < size() の場合、*(begin() + pos) を返す。
    • pos == size() の場合、(1) は charT() の値を持ったオブジェクトへの参照を返す。
    • それ以外の場合は、未定義動作
  • C++11以降

    • pos < size() の場合、*(begin() + pos) を返す。
    • pos == size() の場合、charT() の値を持ったオブジェクトへの参照を返す。
    • それ以外の場合は、未定義動作
    • (2) において、pos == size() の場合に返された参照を charT() 以外の値に書き換えた場合の動作は未定義

例外

投げない

計算量

定数時間

#include <iostream>
#include <string>

int main()
{
  std::string s = "hello";
  char& c = s[1];

  std::cout << c << std::endl;
}

出力

e

参照