Search code examples
c++constructorinitializer-list

Nested initializer list c++


I'm working on a following class representing the 15-puzzle (http://en.wikipedia.org/wiki/15_puzzle) :

class fifteen
{
private: 
   static constexpr size_t dimension = 4;

   using position = std::pair< size_t, size_t > ;

public:
   size_t table [ dimension ][ dimension ];

   size_t open_i;
   size_t open_j;

public:
   fifteen( );

   fifteen( std::initializer_list< std::initializer_list< size_t >> init );
...
}

I'm trying to build the constructor with the given initializer list, however I'm stuck as in I've got no clue how to approach such nested initializer lists. The default constructor looks like this:

fifteen::fifteen()
    :open_i(3), open_j(3)
    {
        for(auto i = 0; i < 16; i++)
            table [i/4] [i%4] = i+1
    }

and the initializer list one would be used like that:

fifteen f{ { 1, 3, 4, 12 }, { 5, 2, 7, 11 }, { 9, 6, 14, 10 }, { 13, 15, 0, 8 } } ;

Does anyone have an idea how can I build such a constructor? Thanks


Solution

  • I managed to do it with the initializer lists, here's how if anyone's interested:

    fifteen( std::initializer_list< std::initializer_list< size_t >> init )
    {
        int pos_i = 0;
        int pos_j = 0;
        for(auto i = init.begin(); i != init.end(); ++i)
        {
            for(auto j = i->begin(); j!= i->end(); ++j)
            {
                table [pos_i][pos_j] = *j;
                pos_j++;
            }
            pos_i++;
            pos_j = 0;
        }
    }