简体   繁体   中英

Initialize C++ array2 using constant array1 known at compile time

I have the following array:

int const A[4] = { 0, 1, 2, 3 };

I want to initialize a duplicate array, as follows:

int a[4] = A;

If I run g++ 4.8.2 on cygwin as follows:

g++ --std=c++11 myfile.cpp

I get the following error:

myfile.cpp:16:16: error: array must be initialized with a brace-enclosed initializer
    int a[4] = A;
               ^

However, evidently " int a[4] = { A }; " isn't going to work either. Is there a way to initialize my array a from A using a simple assignment statement without resorting to:

int a[4] = { A[0], A[1], A[2], A[3] };

?

std::copy(A, A+4, a)

or, by using std::array has the easy copy method you want:

std::array<int, 4>A = {0, 1, 2, 3}
std::array<int, 4>a = A;

Use instead standard class std::array .

#include <array>

//...

const std::array<int, 4> A = { 0, 1, 2, 3 };
std::array<int, 4 > a = A;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM