简体   繁体   English

嵌套初始化列表C ++

[英]Nested initializer list c++

I'm working on a following class representing the 15-puzzle ( http://en.wikipedia.org/wiki/15_puzzle ) : 我正在研究代表15个难题的以下课程( 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. 尝试将您的类更改为使用std::array 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. table更改为std::array<std::array<size_t, 4> 4> ,然后更改构造函数以将std::array<std::array<size_t, 4>, 4>用作输入。 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. 括号初始化可以与std::array一起使用,因此构造函数调用应能够保持不变,但是构造table的后端逻辑将有所不同,并且编译器将能够更好地验证输入的维度。

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)
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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