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

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Categories

Leave a Reply

avatar
  Subscribe  
Notify of