Set array1 = array2 in C++

Viewed 1848

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.

5 Answers

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).

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;

The easiest solution is to use C++, not C.

  std::array<std::array<int,5>,5> arr1 =
     { {1,1},
       {1,2} };

  auto arr2 = arr1;

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;
}

Use std::array instead of raw C arrays: it's a POD and can be copied (copy assignment; overwrites every element of the array with the corresponding element of another array) in a natural manner:

#include <array>
#include <iostream>

int main() {
    using ArrayType = std::array<std::array<int, 2>, 3>;
    ArrayType arr{{
        {1, 2},
        {3, 4},
        {5, 6}
    }};

    ArrayType arr_copy;

    // Copy arr into arr_copy.
    arr_copy = arr;

    // Mutation of original array will not affect the
    // elements of the copy.
    arr[0][0] = 42;
    std::cout << arr_copy[0][0]; // 1 (original value)

    return 0;
}
Related