跳到主要内容

std::string_view at() 方法

// Const version only
constexpr const_reference at( size_type pos ) const;

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

返回指定索引pos处的字符。

执行边界检查。

参数

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

返回值

对所请求字符的引用。

异常

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

复杂度

常数 - O(1)

示例

#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)
本文来源于此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string_view at() 方法

// Const version only
constexpr const_reference at( size_type pos ) const;

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

返回指定索引pos处的字符。

执行边界检查。

参数

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

返回值

对所请求字符的引用。

异常

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

复杂度

常数 - O(1)

示例

#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)
本文来源于此 CppReference 页面。它可能为了改进或编辑者的偏好而进行了修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。