std::array<T,N>::at
來自 cppreference.com
reference at( size_type pos ); |
(1) | (C++11 起) (自 C++17 起為 constexpr) |
const_reference at( size_type pos ) const; |
(2) | (C++11 起) (C++14 起為 constexpr) |
返回指定位置 pos 元素的引用,並進行邊界檢查。
如果 pos 不在容器範圍內,則丟擲 std::out_of_range 型別的異常。
目錄 |
[編輯] 引數
pos | - | 要返回元素的下標 |
[編輯] 返回值
對所請求元素的引用
[編輯] 異常
若 pos >= size(),則為 std::out_of_range。
[編輯] 複雜度
常數時間。
[編輯] 示例
執行此程式碼
#include <chrono> #include <cstddef> #include <iostream> #include <array> #include <stdexcept> int main() { std::array<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 array::at: __n (which is 8) >= _Nm (which is 6) data: 1 88 4 5 5 6
[編輯] 參閱
訪問指定的元素 (public 成員函式) |