Convert a C-style array into a std::array container in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
#include <iostream> #include <array> #include <algorithm> void printContainer(const auto &A) { for (auto i: A) { std::cout << i << ' '; } std::cout << std::endl; } int main() { int arr[] = { 1, 2, 3, 4, 5}; const int n = sizeof(arr) / sizeof(arr[0]); std::array<int, n> first, second; // 1. Using `std::copy` std::copy(std::begin(arr), std::end(arr), first.begin()); printContainer(first); // 2. Using `std::copy_n` std::copy_n(std::begin(arr), n, std::begin(second)); printContainer(second); return 0; } |
2. Using std::move function
We can also use std::move in place of std::copy. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <array> #include <algorithm> int main() { int arr[] = { 1, 2, 3, 4, 5}; const int n = sizeof(arr) / sizeof(arr[0]); std::array<int, n> A; std::move(std::begin(arr), std::end(arr), A.begin()); // print the container return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <array> #include <algorithm> void printContainer(const auto &A) { for (auto i: A) { std::cout << i << ' '; } } int main() { int arr[] = { 1, 2, 3, 4, 5}; const int n = sizeof(arr) / sizeof(arr[0]); // `std::array` is a POD // std::cout << std::is_pod<std::array<int, 5>>::value << std::endl; std::array<int, n> &A = reinterpret_cast<std::array<int, n>&>(arr); printContainer(A); return 0; } |
That’s all about converting a C-style array into a std::array container in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)