Search code examples
c++stdarray

Manipulating std::array in a function


I have a multidimensional array of fixed size in my code, and I need to be able to change the values within it in a separate function. I want to know, are std::arrays passed as references in a method or is a copy made? So can I do this:

using std::array;

void foo (array<array<int,WIDTH>,HEIGHT> bar);
//manipulates the values in the array
...

int main() {
  array<array<int,WIDTH>,HEIGHT> baz;
  ...
  foo(baz);
  //baz is changed
}

Or do I need to explicitly turn it into a reference? I fear that if I created an array function that returned a copy, it would be too messy and not as fast.


Solution

  • Pass by reference (or pointer) if you want to avoid having a copy made:

    void foo (array<array<int,WIDTH>,HEIGHT> &bar);