名稱空間
變體
操作

std::basic_string<CharT,Traits,Allocator>::at

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
std::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"); // for capacity
 
    s = "abc";
    s.at(2) = 'x'; // OK
    std::cout << s << '\n';
 
    std::cout << "string size = " << s.size() << '\n';
    std::cout << "string capacity = " << s.capacity() << '\n';
 
    try
    {
        // This will throw since the requested offset is greater than the current size.
        s.at(3) = 'x';
    }
    catch (std::out_of_range const& exc)
    {
        std::cout << exc.what() << '\n';
    }
}

可能的輸出

abx
string size = 3
string capacity = 7
basic_string::at

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 847 C++98 沒有異常安全保證 添加了強異常安全保證
LWG 2207 C++98 如果 pos >= size()true,則行為未定義 在這種情況下總是丟擲異常

[編輯] 參閱

訪問指定的字元
(public member function) [編輯]
帶邊界檢查訪問指定字元
(std::basic_string_view<CharT,Traits> 的公共成員函式) [編輯]