Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ Array::front() Function



The C++ std::array::front() function is used to return the reference to the first element of the array allowing both read and write operations.

When the front() function is invoked on the empty array, it results in undefined behaviour.

Syntax

Following is the syntax for std::array::front() function.

reference front();
const_reference front() const;

Parameters

It does not accepts any parameter.

Return Value

It returns the first element of an array.

Exceptions

Calling this method on empty array container will cause undefined behavior.

Time complexity

Constant i.e. O(1)

Example 1

In the following example, we are going to consider the basic usage of the front() function.

#include <iostream>
#include <array>
using namespace std;
int main(void) {
   array < int, 5 > arr = {10,20,30,40,50};
   cout << "First element of array = " << arr.front() <<
      endl;
   arr.front() = 1;
   cout << "After modification first element of array = " << arr.front() <<
      endl;
   return 0;
}

Output

Output of the above code is as follows −

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

Example 2

Consider the following example, where we are going to declare a array without size and observing the output.

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < char >
      myarray {'a','b','c','d','e','f','g'};
   cout << myarray.front();
   return 0;
}

Output

Following is the output of the above code −

main.cpp: In function 'int main()':
main.cpp:6:19: error: wrong number of template arguments (1, should be 2)
    6 |         array<char>
      |                   ^
In file included from main.cpp:2:
/usr/include/c++/11/array:95:12: note: provided for 'template<class _Tp, long unsigned int _Nm> struct std::array'
   95 |     struct array
      |            ^~~~~
main.cpp:7:9: error: scalar object 'myarray' requires one element in initializer
    7 |         myarray{ 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
      |         ^~~~~~~
array.htm
Advertisements