C++ Array::at() Function
The C++ std::array::at() function provides a way to access elements in a array with bounds checking. It returns a reference to the element at a specified position within the array.
Unlike the operator[], which does not perform bounds checking, at() throws an out_of_range exception if the provided index is out of the valid range (0 to size-1).
Syntax
Following is the syntax for std::array::at() function.
reference at ( size_type n ); const_reference at ( size_type n ) const;
Parameters
- N − It indicates the position of an element in the array.
Return Value
This function returns the element at the specified position in the array.
Exceptions
This function throws out_of_range expception if value of N is not valid array index.
Time complexity
Constant i.e. O(1)
Example 1
In below example step-1 prints array contents without exception. Step-2 shows exception handling using try-catch block.
#include <iostream>
#include <array>
#include <stdexcept>
using namespace std;
int main(void) {
array < int, 5 > arr = {10, 20, 30, 40, 50};
size_t i;
for (i = 0; i < 5; ++i)
cout << arr.at(i) << " ";
cout << endl;
try {
arr.at(10);
} catch (out_of_range e) {
cout << "out_of_range expcepiton caught for " << e.what() << endl;
}
return 0;
}
Output
Output of the above code is as follows −
10 20 30 40 50 out_of_range expcepiton caught for array::at: __n (which is 10) >= _Nm (which is 5)
Example 2
Consider the following example, where we are going to get the index location of the integer using the at() function.
#include <iostream>
#include <array>
using namespace std;
int main() {
array < int, 10 > arr = {9, 12, 15, 18, 21, 24, 27, 30, 33, 36};
cout << "The location of the element at index 6 = " << arr.at(6) << endl;
return 0;
}
Output
Following is the output of the above code −
The location of the element at index 6 = 27
Example 3
Following is the example, where we are going to find thr array length is lesser than the index location using at() function.
#include <iostream>
#include <array>
using namespace std;
int main() {
array < int, 10 > arr = {9, 12, 15, 18, 21, 24, 27, 30, 33, 36};
cout << "The location of the element at index 20 = " << arr.at(20) << endl;
return 0;
}
Output
If we run the above code it will generate the following output −
terminate called after throwing an instance of 'std::out_of_range' what(): array::at: __n (which is 20) >= _Nm (which is 10) Aborted