3

In C++, is it possible to initialize a built-in array directly from another? As far as I know, one can only have an array and then copy/move each element from another array to it, which is some kind of assignment, not initialization.

Lingxi
  • 14,058
  • 1
  • 35
  • 85

2 Answers2

5

That is one of the new features of the std::array in C++ 11.

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

The latter copies the array a into b.

Itay Grudev
  • 6,684
  • 4
  • 50
  • 84
2

Arrays have neither the copy constructor nor the copy assignment operator. You can only copy elements from one array to another element by element.

Character arrays can be initialized by string literals. Or strings can be copied using standard C functions like strcpy, strncpy, memcpy declared in header <cstring>.

For other arrays you can use for example standard algorithms std::copy, std::copy_if, std::transform declared in header <algorithm>.

Otherwise you can use either standard container std::array or std::vector that allow to assign one object of the type to another object of the same type or create one object from another object.

Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303
  • So, the answer is basically no? – Lingxi Jan 27 '16 at 06:54
  • 2
    @Lingxi For built-in arrays the answer is no, The only approach is to enclose an array inside a structure (this way std::array is designed) and create an object of the structure from another object of the same type that already contains some array that should be copied. – Vlad from Moscow Jan 27 '16 at 06:58