Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

c

c++11

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

like image 893
Gizmo Avatar asked Oct 06 '14 15:10

Gizmo


3 Answers

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;
}
like image 69
juanchopanza Avatar answered Nov 18 '22 19:11

juanchopanza


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

like image 36
capatober Avatar answered Nov 18 '22 19:11

capatober


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

like image 3
Radoslaw Garbacz Avatar answered Nov 18 '22 20:11

Radoslaw Garbacz