Namespaces
Variants

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

From cppreference.net
std::basic_string
CharT & at ( size_type pos ) ;
(1) (自 C++20 起为 constexpr)
const CharT & at ( size_type pos ) const ;
(2) (自 C++20 起为 constexpr)

返回指定位置 pos 处字符的引用。执行边界检查,无效访问时将抛出 std::out_of_range 类型的异常。

目录

参数

pos - 要返回字符的位置

返回值

对请求字符的引用。

异常

pos >= size ( ) 则抛出 std::out_of_range

若因任何原因抛出异常,这些函数将不产生任何效果( 强异常安全保证 )。

复杂度

常量。

示例

#include <iostream>
#include <stdexcept>
#include <string>
int main()
{
    std::string s("message"); // 用于容量
    s = "abc";
    s.at(2) = 'x'; // 正常
    std::cout << s << '\n';
    std::cout << "string size = " << s.size() << '\n';
    std::cout << "string capacity = " << s.capacity() << '\n';
    try
    {
        // 此处将抛出异常,因为请求的偏移量超过当前大小
        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++标准。

缺陷报告 适用标准 发布时行为 正确行为
LWG 847 C++98 未提供异常安全保证 增加强异常安全保证
LWG 2207 C++98 pos >= size ( ) true 时行为未定义 此情况下始终抛出异常

参见

访问指定字符
(公开成员函数)
边界检查访问指定字符
( std::basic_string_view<CharT,Traits> 的公开成员函数)