std::basic_string<CharT,Traits,Allocator>::at
出自cppreference.com
< cpp | string | basic string
CharT& at( size_type pos ); |
(1) | (C++20 起為 constexpr ) |
const CharT& at( size_type pos ) const; |
(2) | (C++20 起為 constexpr ) |
返回到位於指定位置 pos 的字符的引用。進行邊界檢查,非法訪問時拋出 std::out_of_range 類型的異常。
目錄 |
[編輯] 參數
pos | - | 要返回的字符位置 |
[編輯] 返回值
到請求的字符的引用。
[編輯] 異常
在 pos >= size() 時拋出 std::out_of_range。
如果因為任何原因拋出了異常,那麼此函數無效果(強異常安全保證)。
[編輯] 複雜度
常數。
[編輯] 示例
運行此代碼
#include <iostream> #include <stdexcept> #include <string> int main() { std::string s("message"); // 为容量 s = "abc"; s.at(2) = 'x'; // OK std::cout << s << '\n'; std::cout << "字符串大小 = " << s.size() << '\n'; std::cout << "字符串容量 = " << s.capacity() << '\n'; try { // 抛出,即使容量允许访问元素 s.at(3) = 'x'; } catch (std::out_of_range const& exc) { std::cout << exc.what() << '\n'; } }
可能的輸出:
abx 字符串大小 = 3 字符串容量 = 7 basic_string::at
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 出版時的行為 | 正確行為 |
---|---|---|---|
LWG 847 | C++98 | 沒有異常安全保證 | 添加強異常安全保證 |
LWG 2207 | C++98 | pos >= size() 是 true 時的行為未定義 | 此時始終會拋出異常 |
[編輯] 參閱
訪問指定字符 (公開成員函數) | |
訪問指定字符,帶有邊界檢查 ( std::basic_string_view<CharT,Traits> 的公開成員函數)
|