std::basic_string_view<CharT,Traits>::operator[]

来自cppreference.com
 
 
 
 
constexpr const_reference operator[]( size_type pos ) const;
(C++17 起)

返回到位于指定位置 pos 的字符的 const 引用。

如果 pos < size()false,那么行为未定义。

(C++26 前)

如果 pos < size()false,那么:

  • 如果实现是硬化实现,那么就会发生契约违背。并且契约违背处理函数在“观察”求值语义下返回时行为未定义。
  • 如果实现不是硬化实现,那么行为未定义。
(C++26 起)

目录

[编辑] 参数

pos - 要返回的字符位置

[编辑] 返回值

data_ [pos]

[编辑] 异常

不抛出。

[编辑] 复杂度

常数。

[编辑] 注解

std::basic_string::operator[] 不同,std::basic_string_view::operator[](size()) 不会返回到 CharT() 的引用。

[编辑] 示例

#include <iostream>
#include <string_view>
 
int main()
{
    std::string str = "Exemplar";
    std::string_view v = str;
    std::cout << v[2] << '\n';
//  v[2] = 'y'; // 错误:不能通过字符串视图修改
    str[2] = 'y';
    std::cout << v[2] << '\n';
}

输出:

e
y

[编辑] 参阅

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