Namespaces
Variants

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

来自 zh.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> 的公开成员函数)