I have one initialized array arr1
and one declared array arr2
. How can I simply set arr2 = arr1
?
void setup() {
int arr1[5][2]= { {1,1},
{1,2}};
int arr2[5][2];
arr2 = arr1; // Throws error "invalid array assignment"
}
Is it possible to do that in C++? And if so, how? I'd like to prevent using loops for this.
Arrays can't be assigned, but they can be copied (using e.g. std::copy
or std::memcpy
).
A possible better solution is to use std::array
instead, as then you can use plain and simple assignment:
std::array<std::array<int, 2>, 5> arr1 = {{
{ 1, 1 },
{ 1, 2 }
}};
std::array<std::array<int, 2>, 5> arr2;
arr2 = arr1;
You can’t assign C arrays in this way, but you can assign std::array
s and std::vector
s:
auto a1 = std::vector<std::vector<int>>{{1, 1}, {1, 2}};
auto a2 = a1;
(std::array
s work the same way but are more verbose, since you need to specify the number of dimensions as template arguments.)
This example performs copy construction rather than assignment, which is what you’ll want to use 99% of the time. Assignment also works, the same way.
It is worth noting that this is not a multi-dimensional array — it’s a nested array. C++ has no native type for multi-dimensional arrays, but various libraries (mostly for numerical computation) provide them, for instance Eigen and xtensor. These may seem superficially similar to nested arrays, but both their API and their implementation differ in crucial ways. Notably, they are laid out contiguously in memory, which nested vectors aren’t (though nested std::array
s are).
Use std::array:
void setup() {
std::array<std::array<int, 2>, 2> arr1= { {1,1},
{1,2}};
std::array<std::array<int, 2>, 2> arr2;
arr2 = arr1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With