C++ Standard Library C++ STL Library

C++ <array> - operator[]() Function



The C++ array::operator[] function returns 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 does not throw any exception.

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

Syntax

reference operator[] (size_type n);
const_reference operator[] (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 example below, the array::operator[] function returns a reference to the element of the array at the specified position.

#include <iostream>
#include <array>
using namespace std;
 
int main (){
  array<int, 5> MyArray;
  int size = MyArray.size();

  for(int i=0; i<size; i++)
    MyArray[i] = 100*(i+1);

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

  return 0;
}

The output of the above code will be:

MyArray contains: 100 200 300 400 500

❮ C++ <array> Library

5