命名空间
变体
操作

std::basic_string_view<CharT,Traits>::at

来自 cppreference.cn
 
 
 
 
constexpr const_reference at( size_type pos ) const;
(C++17 起)

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

目录

[编辑] 参数

pos - 要返回的字符的位置

[编辑] 返回值

所请求字符的 const 引用。

[编辑] 异常

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

[编辑] 复杂度

常数时间。

[编辑] 示例

#include <iostream>
#include <stdexcept>
#include <string_view>
 
int main()
{
    std::string_view str_view("abcdef");
 
    try
    {
        for (std::size_t i = 0; true; ++i)
            std::cout << i << ": " << str_view.at(i) << '\n';
    }
    catch (const std::out_of_range& e)
    {
        std::cout << "Whooops. Index is out of range.\n";
        std::cout << e.what() << '\n';
    }
}

可能的输出

0: a
1: b
2: c
3: d
4: e
5: f
6: Whooops. Index is out of range.
basic_string_view::at: __pos (which is 6) >= this->size() (which is 6)

[编辑] 亦参见

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