C++ std::array::front
The std::array::front
function provides access to the first element of a std::array
. If the array is empty, the behavior is undefined, so the function should only be used when the array contains at least one element.
Syntax of std::array::front
reference front();
const_reference front() const;
Parameters
The std::array::front
function does not take any parameters.
Return Value
Returns a reference to the first element of the array. If the array is const
, the returned reference is also const
.
Exceptions
The std::array::front
function does not throw exceptions. However, using it on an empty array leads to undefined behavior.
Examples for std::array::front
Example 1: Accessing the First Element Using std::array::front
This example demonstrates how to use the front
function to access the first element of a std::array
:
#include <iostream>
#include <array>
int main() {
std::array<int, 5> arr = {10, 20, 30, 40, 50};
std::cout << "The first element is: " << arr.front() << std::endl;
arr.front() = 100; // Modify the first element
std::cout << "The modified first element is: " << arr.front() << std::endl;
return 0;
}
Explanation:
- A
std::array
namedarr
is initialized with the elements{10, 20, 30, 40, 50}
. - The
front()
function is used to access the first element of the array, which is10
. - The value of the first element is modified using
arr.front() = 100
. - The modified value of the first element (
100
) is displayed.
Output:
The first element is: 10
The modified first element is: 100
Example 2: Undefined Behavior with an Empty Array
Without Exception Handling
This example shows what happens when front()
is used on an empty array:
#include <iostream>
#include <array>
int main() {
std::array<int, 0> arr; // Empty array
// Accessing front() on an empty array (undefined behavior)
std::cout << "The first element is: " << arr.front() << std::endl;
return 0;
}
Explanation:
Since the array is empty, calling front()
results in undefined behavior, potentially causing the program to crash or output garbage values.
Output:
[Undefined behavior: may crash or output garbage]
With Exception Handling
This example demonstrates how to check if the array is empty before calling front()
:
#include <iostream>
#include <array>
int main() {
std::array<int, 0> arr; // Empty array
if (!arr.empty()) {
std::cout << "The first element is: " << arr.front() << std::endl;
} else {
std::cout << "The array is empty. No first element to access." << std::endl;
}
return 0;
}
Explanation:
- The program checks if the array is empty using
empty()
. - If the array is not empty,
front()
is called to access the first element. - If the array is empty, a message is displayed, avoiding undefined behavior.
Output:
The array is empty. No first element to access.