C ++ STL中的数组at()函数

数组是存储在连续内存位置中的相同数据类型元素的集合。

在c ++标准库(STL)中,有很多方法可以支持数组的功能。 其中之一是数组at()方法。

数组at()方法用于返回位于特定索引值的元素的引用。

语法

数组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