Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, is it possible to initialize an array directly from another?

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.

like image 671
Lingxi Avatar asked Oct 28 '25 09:10

Lingxi


2 Answers

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.

like image 95
Itay Grudev Avatar answered Oct 31 '25 01:10

Itay Grudev


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.

like image 22
Vlad from Moscow Avatar answered Oct 31 '25 02:10

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!