array at() function in C++ STL
The array::at() is a built-in function in C++ STL which returns a reference to the element present at location i in given array. Syntax:
array_name.at(i)
Parameters: The function accepts a single mandatory parameter i which specifies the location. Return value: The function returns an element present at index i in given array if i is valid index otherwise it throws out_of_range exception. Time Complexity: O(1) Below programs demonstrate the array::at() function: Program 1:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
array< int , 5> arr = { 1, 5, 2, 4, 7 };
cout << "The element at index 2 is " << arr.at(2) << endl;
return 0;
}
|
Output:
The element at index 2 is 2
Program 2 : Illustrating function when it is implemented on lesser size array causing an error.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
array< int , 5> arr = { 1, 5, 2, 4, 7 };
cout << "The element at index 7 is " << arr.at(7) << endl;
return 0;
}
|
Output:
Abort signal from abort(3) (SIGABRT)
Last Updated :
13 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...