Standard Template Library: Using the Array front()
Method
What is it?
front()
is a method of the C++ Standard Template Library (STL) array
class. It is used to access the first element of the array.
Syntax
T& front();
const T& front() const;
How to use it
To use front()
, you must first create an array
object. Then, you can call the method on the object to get the first element of the array.
Program code snippet example
#include <iostream>
#include <array>
using namespace std;
int main() {
array<int, 5> myArray {1, 2, 3, 4, 5};
int firstElement = myArray.front();
cout << "The first element of the array is: " << firstElement << endl;
return 0;
}
In the example above, we create an array
object called myArray
with 5 elements. Then, we initialize the array with the values 1
, 2
, 3
, 4
, and 5
.
Then, we call the front()
method on myArray
to get the first element of the array. Finally, we store the result in the variable firstElement
and print it to the console. The output of this program will be:
The first element of the array is: 1
Output the array arr
first element using the front()
method.