This post will discuss how to convert a C-style array into a std::array container in C++.

C++ doesn’t provide any straight conversion from an array to std::array. This is because the std::array class comprises aggregate types and has no custom constructors. So std::array can be constructed using the class member functions such as copy, move, or by using initializer lists, otherwise each of the elements will be default-initialized.

1. Using std::copy or std::n_copy function

The idea is to copy all elements from the given array to std::array using standard algorithms std::copy or std::n_copy from the algorithm header. This is demonstrated below:

Download  Run Code

2. Using std::move function

We can also use std::move in place of std::copy. This is demonstrated below:

Download  Run Code

3. Using reinterpret_cast function

Another way to copy all elements from the given array to std::array is to use the reinterpret_cast. We should best avoid this function as C++ standard offers very few guarantees about reinterpret_cast behavior.

The following code works because a std::array class is POD (Plain Old Data) type and its memory layout requirements match with that of a standard array.

Download  Run Code

That’s all about converting a C-style array into a std::array container in C++.