Namespaces
Variants

std::basic_string<CharT,Traits,Allocator>::at

ja.cppreference.net より
 
 
 
std::basic_string
 
CharT& at( size_type pos );
(1) (constexpr C++20以上)
const CharT& at( size_type pos ) const;
(2) (constexpr C++20以上)

指定された位置 pos の文字への参照を返します。境界チェックが行われ、無効なアクセスがあった場合は std::out_of_range 型の例外がスローされます。

パラメータ

pos - 返される文字の位置

戻り値

要求された文字への参照。

例外

std::out_of_range をスローする( pos >= size ( ) の場合)。

何らかの理由で例外がスローされた場合、これらの関数は何も効果を持ちません( strong exception safety guarantee )。

計算量

定数。

例

#include <iostream>
#include <stdexcept>
#include <string>
int main()
{
    std::string s("message"); // for capacity
    s = "abc";
    s.at(2) = 'x'; // OK
    std::cout << s << '\n';
    std::cout << "string size = " << s.size() << '\n';
    std::cout << "string capacity = " << s.capacity() << '\n';
    try
    {
        // This will throw since the requested offset is greater than the current size.
        s.at(3) = 'x';
    }
    catch (std::out_of_range const& exc)
    {
        std::cout << exc.what() << '\n';
    }
}

出力例:

abx
string size = 3
string capacity = 7
basic_string::at

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 847 C++98 例外安全性保証が存在しなかった 強い例外安全性保証を追加
LWG 2207 C++98 動作は未定義であった( pos >= size ( ) が true の場合) この場合、常に例外をスローする

関連項目

指定された文字にアクセスする
(公開メンバ関数)
境界チェック付きで指定された文字にアクセスする
(std::basic_string_view<CharT,Traits>の公開メンバ関数)