C++ STL 中的 array at() 函数
数组是存储在连续内存位置中具有相同数据类型的一系列元素。
在 c++ 标准库 (STL) 中有许多方法来支持数组的功能。其中一种是 array 的 at() 方法。
array at() 方法用于返回特定索引值处的元素的引用。
语法
编写 array at() 函数的一般语法为
array_name.at(i);
参数
该函数接受一个参数,该参数是函数访问的元素的索引。
返回
该函数返回在调用时传递其索引的元素。如果传递了任何无效的索引值,函数将抛出 out_of_range 异常。
示例
演示 Array::At() 函数工作原理的程序 −
#include <bits/stdc++.h>
using namespace std;
int main(){
array<float, 4> arr = { 12.1, 67.3, 45.0, 89.1 };
cout << "The element at index 1 is " << arr.at(1) << endl;
return 0;
}输出
The element at index 1 is 67.3
示例
当索引值大于数组长度时说明错误的程序 −
#include <bits/stdc++.h>
using namespace std;
int main(){
array<float, 4> arr = { 12.1, 67.3, 45.0, 89.1 };
cout << "The element at index 1 is " << arr.at(8) << endl;
return 0;
}输出
terminate called after throwing an instance of 'std::out_of_range' what(): array::at: __n (which is 8) >= _Nm (which is 4) The element at index 1 is Aborted
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP