Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ array::at function is used to return a reference to the element of the array at the specified position. If the specified position is not within the bounds of valid elements in the array, the function throws an out_of_range exception.

Note: The array::at function produces the same result as array::operator[] function, except array::operator[] does not check the specified position against bounds of valid elements in the array.

Syntax

reference at (size_type n);
const_reference at (size_type n) const;

Parameters

n Specify position of the element in the array.

Return Value

The element at the specified position in the array.

Time Complexity

Constant i.e, Θ(1).

Example:

In the below example, the array::at function is used to return a reference to the element of the array called MyArray at the specified positions.

#include <iostream>
#include <array>
using namespace std;
 
int main (){
  array<int, 5> MyArray{10, 20, 30, 40, 50};

  cout<<"MyArray contains: ";
  for(int i = 0; i < MyArray.size(); i++)
    cout<<MyArray.at(i)<<" ";

  return 0;
}

The output of the above code will be:

MyArray contains: 10 20 30 40 50 

❮ C++ - Array