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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// the array::at() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // array initialisation
    array<int, 5> arr = { 1, 5, 2, 4, 7 };
  
    // prints the element at ith index
    // index starts from zero
    cout << "The element at index 2 is " << arr.at(2) << endl;
  
    return 0;
}

chevron_right


Output:

The element at index 2 is 2
Program 2 : Illustrating function when it is implemented on lesser size array causing an error.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate
// the array::at() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // array initialisation
    array<int, 5> arr = { 1, 5, 2, 4, 7 };
  
    // it is an exception
    cout << "The element at index 2 is " << arr.at(7) << endl;
  
    return 0;
}

chevron_right


Output:

Abort signal from abort(3) (SIGABRT)


My Personal Notes arrow_drop_up

pawanasipugmailcom

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.