Open In App

array at() function in C++ STL

Improve
Improve
Like Article
Like
Save
Share
Report

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




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




// 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 7 is " << arr.at(7) << endl;
 
    return 0;
}


Output:

Abort signal from abort(3) (SIGABRT)


Last Updated : 13 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads