C++ Array Library - front() Function


The C++ function std::array::front() returns reference to the first element of the array container. If array size is zero then behavior of this method is undefined. Unlike begin() method this method returns first element itself and not iterator.


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

reference front();
const_reference front() cont;



Return Value

Returns the first element of an array. If array object is const-qualified this method return const reference otherwise it returns reference.


This member function never throws exception. Calling this method on empty array container will cause undefined behavior.

Time complexity

Constant i.e. O(1)


The following example shows the usage of std::array::front() function.

#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 5> arr = {10, 20, 30, 40, 50};

   /* print first element */
   cout << "First element of array                    = " << arr.front() 
      << endl;

   /* modify value */
   arr.front() = 1;

   /* print modified value */
   cout << "After modification first element of array = " << arr.front() 
      << endl;

   return 0;

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

First element of array                    = 10
After modification first element of array = 1