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
.