Skip to content
Related Articles

Related Articles

array at() function in C++ STL
  • Last Updated : 29 Aug, 2018

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


Output:

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




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


Output:

Abort signal from abort(3) (SIGABRT)

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :