2

I have this array in the class and I need to assign 9*9 number matrix to it.

class puzzle{

    int gme[9][9];
}

I know it is not possible to assign an array in c++ with the braze enclosed initialization: Mentioned in this question: c++ array assignment of multiple values

It is possible to use std::copy(newgme, newgme + 3, gme); and assign the array.

I don't want to do this because we need to assign the array newgme outside the class and pass this as a parameter to the member function.

Array assignment of multiple values in a class: Which is the best practice?

I would like to set the values to these without using vectors:

                        0,0,7   ,0,0,0    ,4,0,6,
                        8,0,0   ,4,0,0    ,1,7,0,
                        0,0,0   ,3,0,0    ,9,0,5,

                        0,0,0   ,7,0,5    ,0,0,8,
                        0,0,0   ,0,0,0    ,0,0,0,
                        4,0,0   ,2,0,8    ,0,0,0,

                        7,0,4   ,0,0,3    ,0,0,0,
                        0,5,2   ,0,0,1    ,0,0,9,
                        1,0,8   ,0,0,0    ,6,0,0
Community
  • 1
  • 1
Indra
  • 1,308
  • 3
  • 18
  • 24

2 Answers2

3

Unfortunately, std::copy won't work because the nested array int[9] is not itself assignable. Some people might advise to alias the multidimensional array as an int[81] but this is undefined behaviour.

Your best bet is probably to use a nested std::array:

std::array<std::array<int, 9>, 9> gme;

Future versions of C++ may have a multidimensional array type.

Another option is Boost.MultiArray, although that has dynamic extents (and therefore uses dynamic memory allocation).

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • I tried as you told but got this error:'array' in namespace 'std' does not name a type. I added `#include` and got this error: `#error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.` This method is supported by ISO c++ 2011 standards only? And you suggest this is the best method? – Indra Feb 28 '14 at 19:47
1

I assume newgme is declared this way:

int newgme[9][9];

In such a case, you can use memcpy:

void puzzle::set_gme(int newgme[9][9])
{
    memcpy(gme, newgme, sizeof(gme));
}

memcpy is a library function inherited from C; it only works on POD types, which happens to be exactly your case (explained in a great length in this answer).

Community
  • 1
  • 1
anatolyg
  • 26,506
  • 9
  • 60
  • 134