array at() function in C++ STL

C++Server Side ProgrammingProgramming

An array is a collection of elements of the same data type stored in continuous memory locations.

In c++ standard library (STL) there are a lot of methods to support the functioning of the array. One of them is an array at() method.

The array at() method is used to return the reference of the element at a specific index value.

Syntax

The general syntax for array at() function is

array_name.at(i);

Parameters

The function accepts a single parameter which I the index of the element which is to be accessed using the function.

Returns

The function returns the element whose index is passed at the time of calling it. If any invalid index value is passed the function throws out_of_range exception.

Example

Program To Demonstrate The Working Of Array::At() Function −

 Live Demo

#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;
}

Output

The element at index 1 is 67.3

Example

Program To Illustrate Error When Index Value Is Greater Than Array Length −

 Live Demo

#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;
}

Output

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
raja
Published on 24-Oct-2019 12:20:35
Advertisements