C++ Array Library - operator[] Function



Description

The C++ function std::array::operator[] returns reference to the element present at location n in a given array container. This method doesn't check for array bounds. Accessing element other than valid array bounds will cause undefined behavior.

Declaration

Following is the declaration for std::array::operator[] function form std::array header.

reference operator[](size_type n);
const_reference operator[](size_type n) const;

Parameters

n − index of the element in array.

Return Value

Return a reference to the element present at location n in a given array container.

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

Exceptions

This member function never throws exception if value of n is valid array index, otherwise behavior is undefined.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::array::operator[] function.

#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 5> arr = {1, 2, 3, 4, 5};

   /* iterator array using [] operator */
   for (size_t i = 0; i < 5; ++i)
      cout << arr[i] << " ";
   cout << endl;

   /* assing new value to the first array element */
   arr[0] = 10;

   /* print modified array */
   for (size_t i = 0; i < 5; ++i)
      cout << arr[i] << " ";
   cout << endl;

   return 0;
}

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

1 2 3 4 5 
10 2 3 4 5 
array.htm
Advertisements