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

来自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
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'; // OK
    std::cout << s << '\n';
 
    std::cout << "字符串大小 = " << s.size() << '\n';
    std::cout << "字符串容量 = " << s.capacity() << '\n';
 
    try
    {
        // 抛出,即使容量允许访问元素
        s.at(3) = 'x';
    }
    catch (std::out_of_range const& exc)
    {
        std::cout << exc.what() << '\n';
    }
}

可能的输出:

abx
字符串大小 = 3
字符串容量 = 7
basic_string::at

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 847 C++98 没有异常安全保证 添加强异常安全保证
LWG 2207 C++98 pos >= size()true 时的行为未定义 此时始终会抛出异常

[编辑] 参阅

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