跳到主要内容

std::string_view operator[]

// Const version only
constexpr const_reference operator[]( size_type pos ) const;

返回对指定索引pos处元素的引用

执行边界检查。

注意

不执行边界检查,使用越界元素是未定义行为

.

参数

  • pos - 要返回的字符的位置

返回值

对所请求字符的引用。

异常

(无)

复杂度

常数 - O(1)

备注

std::basic_string::operator[] 不同,std::basic_string_view::operator[](size()) 会导致未定义行为

而不是返回 CharT()

示例

Main.cpp
#include <iostream>
#include <string_view>
int main()
{
std::string str = "Exemplar";
std::string_view v = str;
std::cout << v[2] << '\n';
// v[2] = 'y'; // Error: cannot modify through a string view
str[2] = 'y';
std::cout << v[2] << '\n';
}
输出
e
y
本文源自 此 CppReference 页面。它可能为了改进或编辑偏好而有所改动。点击“编辑此页面”可查看对本文档所做的所有更改。
悬停查看原始许可证。

std::string_view operator[]

// Const version only
constexpr const_reference operator[]( size_type pos ) const;

返回对指定索引pos处元素的引用

执行边界检查。

注意

不执行边界检查,使用越界元素是未定义行为

.

参数

  • pos - 要返回的字符的位置

返回值

对所请求字符的引用。

异常

(无)

复杂度

常数 - O(1)

备注

std::basic_string::operator[] 不同,std::basic_string_view::operator[](size()) 会导致未定义行为

而不是返回 CharT()

示例

Main.cpp
#include <iostream>
#include <string_view>
int main()
{
std::string str = "Exemplar";
std::string_view v = str;
std::cout << v[2] << '\n';
// v[2] = 'y'; // Error: cannot modify through a string view
str[2] = 'y';
std::cout << v[2] << '\n';
}
输出
e
y
本文源自 此 CppReference 页面。它可能为了改进或编辑偏好而有所改动。点击“编辑此页面”可查看对本文档所做的所有更改。
悬停查看原始许可证。