命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 容器‎ | array
 
 
 
 
reference at( size_type pos );
(1) (since C++11)
(constexpr since C++17)
const_reference at( size_type pos ) const;
(2) (since C++11)
(constexpr since C++14)

返回对指定位置 pos 处元素的引用,带有边界检查。

如果 pos 不在容器的范围内,则抛出 std::out_of_range 类型的异常。

目录

[编辑] 参数

pos - 要返回的元素的位置

[编辑] 返回值

对请求元素的引用

[编辑] 异常

std::out_of_range 如果 pos >= size()

[编辑] 复杂度

常量。

[编辑] 示例

#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

[编辑] 参见

访问指定的元素
(公共成员函数) [编辑]