名稱空間
變體
操作

std::inplace_vector<T,N>::at

來自 cppreference.com
 
 
 
 
constexpr reference at( size_type pos );
(1) (C++26 起)
constexpr const_reference at( size_type pos ) const;
(2) (C++26 起)

返回指定位置 pos 元素的引用,並進行邊界檢查。

如果 pos 不在容器的範圍內,則丟擲 std::out_of_range 型別的異常。

目錄

[編輯] 引數

pos - 要返回元素的下標

[編輯] 返回值

對所請求元素的引用

[編輯] 異常

如果 pos >= size(),則為 std::out_of_range

[編輯] 複雜度

常數時間。

[編輯] 示例

#include <chrono>
#include <cstddef>
#include <iostream>
#include <inplace_vector>
#include <stdexcept>
 
int main()
{
    std::inplace_vector<int, 6> data{1, 2, 4, 5, 5, 6};
 
    // Set element 1
    data.at(1) = 88;
 
    // Read element 2
    std::cout << "Element at index 2 has value " << data.at(2) << '\n';
 
    std::cout << "data size = " << data.size() << '\n';
 
    try
    {
        // Try to set an element at random position >= size()
        auto moon_phase = []
        {
            return std::chrono::system_clock::now().time_since_epoch().count() % 8;
        };
        data.at(data.size() + moon_phase()) = 13;
    }
    catch(const std::out_of_range& ex)
    {
        std::cout << ex.what() << '\n';
    }
 
    // Print final values
    std::cout << "data:";
    for (int elem : data)
        std::cout << ' ' << elem;
    std::cout << '\n';
}

可能的輸出

Element at index 2 has value 4
data size = 6
std::out_of_range: pos (which is 8) >= size() (which is 6)
data: 1 88 4 5 5 6

[編輯] 參閱

訪問指定的元素
(公共成員函式) [編輯]