C++ Array Library - at() Function



Description

The C++ function std::array::at() returns a reference to the element present at location N in given array container.

Declaration

Following is the declaration for std::array::at() function form std::array header.

reference at(size_type n);
cont_referece at(size_t n) const;

Parameters

N − index of an element in the array.

Return Value

Returns a element present at index N in given array if N is valid index otherwise throws out_of_range exception.

If array object is const-qualified method returns const reference otherwise it returns reference.

Exceptions

This member function throws out_of_range expception if value of N is not valid array index.

Time complexity

Constant i.e. O(1)

Example

In below example step-1 prints array contents without exception. Step-2 shows exception handling using try-catch block.

#include <iostream>
#include <array>
#include <stdexcept>

using namespace std;

int main(void) {
   array<int, 5> arr = {10, 20, 30, 40, 50};
   size_t i;

   /* print array contents */
   for (i = 0; i < 5; ++i)
      cout << arr.at(i) << " ";
   cout << endl;

   /* generate out_of_range exception. */
   try {
      arr.at(10);
   } catch(out_of_range e) {
      cout << "out_of_range expcepiton caught for " << e.what() << endl;
   }

   return 0;
}

Let us compile and run the above program, this will produce the following result −

10 20 30 40 50 
out_of_range expcepiton caught for array::at: __n (which is 10) >= _Nm (which is 5)
array.htm
Advertisements