Assign C array to C++'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U]" to "std::array<T,U>" Assign C array to C++'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U]" to "std::array<T,U>" arrays arrays

Assign C array to C++'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U]" to "std::array<T,U>"


There is no conversion from plain array to std::array, but you can copy the elements from one to the other:

std::copy(std::begin(X), std::end(X), std::begin(Y));

Here's a working example:

#include <iostream>#include <array>#include <algorithm>  // std::copyint main() {    int X[8] = {0,1,2,3,4,5,6,7};    std::array<int,8> Y;    std::copy(std::begin(X), std::end(X), std::begin(Y));    for (int i: Y)        std::cout << i << " ";    std::cout << '\n';    return 0;}


I know it's been a while, but maybe still useful (for somebody).The provided above solutions are great, however maybe you'd be interested in a less elegant, but possibly a faster one:

    #include <array>    #include <string.h>        using namespace std;     double A[4] = {1,2,3,4};    array<double, 4> B;    memcpy(B.data(), A, 4*sizeof(double));

The array size can be determined in some other (more dynamic) ways when needed, here is just an idea. I have not tested the performance of both solutions.

The one proposed here requires to provide proper size, otherwise bad things can happen.

Edit:
Comments below made me do the tests and unless someone is really trying to squeeze max of the performance it's not worth it (test copied back and forth per loop):
B size:100000 tested copy vs memcpy on 100000 elements arrays with 100000 loop count:
** copy() = 9.4986 sec
** memcpy() = 9.45058 sec
B size:100000 tested copy vs memcpy on 100000 elements arrays with 100000 loop count:
** copy() = 8.88585 sec
** memcpy() = 9.01923 sec
B size:100000 tested copy vs memcpy on 100000 elements arrays with 100000 loop count:
** copy() = 8.64099 sec
** memcpy() = 8.62316 sec
B size:100000 tested copy vs memcpy on 100000 elements arrays with 100000 loop count:
** copy() = 8.97016 sec
** memcpy() = 8.76941 sec