Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set array1 = array2 in C++

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.

like image 582
alve89 Avatar asked Mar 03 '20 13:03

alve89


3 Answers

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;
like image 112
Some programmer dude Avatar answered Sep 17 '22 09:09

Some programmer dude


You can’t assign C arrays in this way, but you can assign std::arrays and std::vectors:

auto a1 = std::vector<std::vector<int>>{{1, 1}, {1, 2}};
auto a2 = a1;

(std::arrays 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::arrays are).

like image 20
Konrad Rudolph Avatar answered Sep 19 '22 09:09

Konrad Rudolph


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;
}
like image 28
Thomas Sablik Avatar answered Sep 20 '22 09:09

Thomas Sablik