Convert a C-style array into a std::array container in C++

In this post, we will see 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 std::array class is made out of aggregate types, and have no custom constructors. So std::array can be constructed using the class member functions such as copy, move, or by using initializer lists, else each of the elements will be default-initialized.

 

1. std::copy or std::n_copy

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. std::move

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

 

Download   Run Code

 

3. reinterpret_cast

Another way to copy all elements from the given array to std::array is to use reinterpret_cast. This method should be best avoided as C++ standard offers a very few guarantees about reinterpret_cast behavior.

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

 

Download   Run Code

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of