描述
C++ 函数std::array::at()返回对给定数组容器中位置 N 处元素的引用。
声明
以下是 std::array::at() 函数形式 std::array 标头的声明。
reference at(size_type n);
cont_referece at(size_t n) const;
参数
N- 数组中元素的索引。
返回值
如果 N 是有效索引,则返回存在于给定数组中索引 N 处的元素,否则抛出out_of_range异常。
如果数组对象是 const-qualified 方法返回常量引用,否则返回引用。
异常
这个成员函数抛出out_of_range如果 N 的值不是有效的数组索引,则异常。
时间复杂度
常数,即 O(1)
示例
在下面的示例中,步骤 1 无一例外地打印数组内容。步骤 2 显示了使用 try-catch 块的异常处理。
#include <iostream>
#include <array>
#include <stdexcept>
using namespace std;
int main(void) {
array<int, 5> arr = {10, 20, 30, 40, 50};
size_t i;
/* print array contents */
for (i = 0; i < 5; ++i)
cout << arr.at(i) << " ";
cout << endl;
/* generate out_of_range exception. */
try {
arr.at(10);
} catch(out_of_range e) {
cout << "out_of_range expcepiton caught for " << e.what() << endl;
}
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果——
10 20 30 40 50
out_of_range expcepiton caught for array::at:__n (which is 10) >= _Nm (which is 5)
相关用法
- C++ Array swap()用法及代码示例
- C++ Array max_size()用法及代码示例
- C++ Array get()用法及代码示例
- C++ Array back()用法及代码示例
- C++ Array data()用法及代码示例
- C++ Array empty()用法及代码示例
- C++ Array tuple_size()用法及代码示例
- C++ Array fill()用法及代码示例
- C++ Array cbegin()用法及代码示例
- C++ Array cend()用法及代码示例
- C++ Array end()用法及代码示例
- C++ Array rbegin()用法及代码示例
- C++ Array begin()用法及代码示例
- C++ Array crend()用法及代码示例
- C++ Array size()用法及代码示例
- C++ Array rend()用法及代码示例
- C++ Array front()用法及代码示例
- C++ Array crbegin()用法及代码示例
- C++ Algorithm copy()用法及代码示例
- C++ Algorithm remove_if()用法及代码示例
注:本文由纯净天空筛选整理自 C++ Array Library - at() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。