C++ Array 库 - operator[] 函数
描述
C++ 函数 std::array::operator[] 返回对给定数组容器中位置 n 处元素的引用。 此方法不检查数组边界。 访问有效数组边界以外的元素将导致未定义的行为。
声明
以下是 std::array::operator[] 函数形式 std::array 头的声明。
reference operator[](size_type n); const_reference operator[](size_type n) const;
参数
n − 数组中元素的索引。
返回值
返回对给定数组容器中位置 n 处元素的引用。
如果数组对象是 const 限定的,则该方法返回 const 引用,否则返回引用。
异常
如果 n 的值是有效的数组索引,则此成员函数永远不会引发异常,否则行为 undefined。
时间复杂度
常数,即 O(1)
示例
以下示例显示了 std::array::operator[] 函数的用法。
#include <iostream>
#include <array>
using namespace std;
int main(void) {
array<int, 5> arr = {1, 2, 3, 4, 5};
/* iterator array using [] operator */
for (size_t i = 0; i < 5; ++i)
cout << arr[i] << " ";
cout << endl;
/* assing new value to the first array element */
arr[0] = 10;
/* print modified array */
for (size_t i = 0; i < 5; ++i)
cout << arr[i] << " ";
cout << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
1 2 3 4 5 10 2 3 4 5

