命名空间
变体
操作

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

来自 cppreference.cn
< 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"); // 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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 847 C++98 没有异常安全保证 添加了强异常安全保证
LWG 2207 C++98 如果 pos >= size()true,则行为未定义 在这种情况下总是抛出异常

[编辑] 参阅

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