std::basic_string_view<CharT,Traits>::at
出自cppreference.com
| |
(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)
參閱
| 訪問指定字符 (公開成員函數) | |
| 訪問指定字符,有邊界檢查 ( std::basic_string<CharT,Traits,Allocator> 的公開成員函數)
|