C++ Array Library - front() Function



Description

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.

Declaration

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

reference front();
const_reference front() cont;

Parameters

None

Return Value

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

Exceptions

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

Time complexity

Constant i.e. O(1)

Example

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
array.htm
Advertisements