How do I iterate safely and efficiently with std::array?

Iterating through a `std::array` in C++ can be done safely and efficiently using various methods provided by the standard library. Here are a few examples of how to achieve this:

1. Using a Range-Based For Loop

The range-based for loop is a concise way to iterate through the elements of a `std::array`.

#include <iostream> #include <array> int main() { std::array arr = {1, 2, 3, 4, 5}; for (const auto& element : arr) { std::cout << element << " "; } return 0; }

2. Using Iterators

You can also use iterators to traverse the `std::array`, which provides more flexibility for certain algorithms.

#include <iostream> #include <array> int main() { std::array arr = {1, 2, 3, 4, 5}; for (auto it = arr.begin(); it != arr.end(); ++it) { std::cout << *it << " "; } return 0; }

3. Using std::for_each

The `std::for_each` algorithm can be used for a more functional style of iteration.

#include <iostream> #include <array> #include <algorithm> int main() { std::array arr = {1, 2, 3, 4, 5}; std::for_each(arr.begin(), arr.end(), [](int element) { std::cout << element << " "; }); return 0; }

std::array C++ iteration safe iteration efficient iteration range-based for loop iterators std::for_each C++ standards