4

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,579
  • 2
  • 37
  • 93
  • 1
    Have you read http://stackoverflow.com/questions/20519992/array-declaration-and-initialization-in-c11 ? – VolAnd Jan 27 '16 at 06:34
  • 3
    Are you concerned about inbuilt arrays a la `int n[5]`, and/or `std::array<>`s? – Tony Delroy Jan 27 '16 at 06:35
  • @TonyD I mean built-in array. – Lingxi Jan 27 '16 at 06:37
  • Could you please make your question more clearly ? Add some pseudo for example – Van Tr Jan 27 '16 at 06:39
  • 1
    @Lingxi `std::array` was introduced by C++11 as a convenient wrapper atop built-in arrays; it provides both the copy constructor and copy assignment operator, so you don't have to do it manually. – legends2k Jan 27 '16 at 07:00
  • @legends2k I'm surprised that noone commented on that, but you don't have to do that manually - it's behaviour of a trivial struct (no user-defined copy operation). What actually this class does, is introduction of safe operator[] and iterator – Swift - Friday Pie Dec 26 '22 at 11:58

2 Answers2

6

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
  • 7,055
  • 4
  • 54
  • 86
4

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
  • 301,070
  • 26
  • 186
  • 335
  • 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