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>"

23,116

Solution 1

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::copy

int 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;
}

Solution 2

C++20 has std::to_array function

So, the code is

int X[8];
std::array<int, 8> Y = std::to_array(X);

https://godbolt.org/z/Efsrvzs7Y

Solution 3

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

Share:
23,116
Gizmo
Author by

Gizmo

Edited.

Updated on October 29, 2021

Comments

  • Gizmo
    Gizmo over 2 years

    I am trying to assign a C array to a C++ std::array.

    How do I do that, the cleanest way and without making unneeded copies etc?

    When doing

    int X[8];
    std::array<int,8> Y = X;
    

    I get an compiler error: "no suitable constructor exists".