In C++, is it possible to initialize an array dire

2020-04-16 06:09发布

问题:

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.

回答1:

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.



回答2:

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.