std::basic_string<CharT,Traits,Allocator>::operator[]
From cppreference.com
< cpp | string | basic string
CharT& operator[]( size_type pos ); |
(1) | (C++20 以降 constexpr) |
const CharT& operator[]( size_type pos ) const; |
(2) | (C++20 以降 constexpr) |
pos < size() の場合、指定された位置 pos の文字への参照を返します。また、pos == size() の場合、CharT() への参照を返します。境界チェックは行われません。
pos > size() の場合、動作は未定義です。
オーバーロード (1) の場合、pos == size() で、返された参照が指すオブジェクトが CharT() 以外の値に変更された場合、動作は未定義です(C++11 以降)。
目次 |
[編集] Parameters
| pos | - | 返される文字の位置 |
[編集] Return value
pos < size() の場合、要求された要素への参照。または、pos == size() の場合、CharT() への参照。
[編集] Complexity
定数。
[編集] Example
このコードを実行
#include <iostream> #include <string> int main() { const std::string e("Exemplar"); for (unsigned i = e.length() - 1; i != 0; i /= 2) std::cout << e[i]; std::cout << '\n'; const char* c = &e[0]; std::cout << c << '\n'; // print as a C string // Change the last character of s into a 'y' std::string s("Exemplar "); s[s.size() - 1] = 'y'; // equivalent to s.back() = 'y'; std::cout << s << '\n'; }
出力
rmx Exemplar Exemplary
[編集] Defect reports
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 259 | C++98 | 非 const オーバーロードが、不正な `data()[pos]` を返す可能性があった | 次のように変更された: *(begin() + pos) |
| LWG 2475 | C++11 | もし pos == size() で、返された参照が指すオブジェクトを変更する動作は未定義だった。 未定義 |
次のように修正された: CharT() へ変更 |
[編集] See also
| 境界チェック付きで指定された文字にアクセスする (public member function) | |
| (DR*) |
最初の文字にアクセスする (public member function) |
| (DR*) |
最後の文字にアクセスする (public member function) |
| 指定された文字にアクセスする (public member function of std::basic_string_view<CharT,Traits>) |