命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
CharT& at( size_type pos );
(1) (constexpr since C++20)
const CharT& at( size_type pos ) const;
(2) (constexpr since C++20)

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

内容

[编辑] 参数

pos - 要返回的字符的位置

[编辑] 返回值

对请求字符的引用。

[编辑] 异常

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

如果由于任何原因抛出异常,这些函数不起作用(强异常安全保证)。

[编辑] 复杂度

常数。

[编辑] 示例

#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,则行为未定义 在这种情况下始终抛出异常

[编辑] 参见

访问指定的字符
(public member function) [编辑]
访问指定的字符,并进行边界检查
(public member function of std::basic_string_view<CharT,Traits>) [编辑]