std::string_view operator[]
- 自 C++17 起
// 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