简体   繁体   中英

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

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

Try changing your class to use std::array instead. Change table to std::array<std::array<size_t, 4> 4> , and change your constructor to take a std::array<std::array<size_t, 4>, 4> as input. Brace initialization can be used with std::array , so your constructor call should be able to stay the same, but the backend logic to construct table would be different, and the compiler would be able to better validate the dimensions of the input.

Try something like this:

class fifteen
{
private: 
    using position = std::pair< size_t, size_t > ;

public:
    static constexpr size_t dimension = 4;
    using tablearr = std::array< std::array< size_t, dimension >, dimension >;

    tablearr table;

    size_t open_i;
    size_t open_j;

public:
    fifteen( );

    fifteen( tablearr const &init );
    //...
}


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

fifteen::fifteen(tablearr const &init)
    : table(init), open_i(3), open_j(3)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM