C++ 参考手册

位置:首页 > C++ 参考手册 >容器库 >std::array > std::array<T,N>::operator[]

reference operator[]( size_type pos );
(C++17 前)
constexpr reference operator[]( size_type pos );
(C++17 起)
const_reference operator[]( size_type pos ) const;
(C++14 前)
constexpr const_reference operator[]( size_type pos ) const;
(C++14 起)

返回位于指定位置 pos 的元素的引用。不进行边界检查。

参数

pos - 要返回的元素的位置

返回值

到所需元素的引用。

复杂度

常数。

注意

不同于 std::map::operator[] ,此运算符决不插入新元素到容器。通过此运算符访问不存在的元素是未定义行为。

示例

下列代码使用 operator[] 读取并写入 std::array<int>

#include <array>
#include <iostream>
 
int main()
{
    std::array<int,4> numbers {2, 4, 6, 8};
 
    std::cout << "Second element: " << numbers[1] << '\n';
 
    numbers[0] = 5;
 
    std::cout << "All numbers:";
    for (auto i : numbers) {
        std::cout << ' ' << i;
    }
    std::cout << '\n';
}

输出:

Second element: 4
All numbers: 5 4 6 8

参阅

访问指定的元素,同时进行越界检查
(公开成员函数)