初始化类型为枚举类的二维std ::数组(C++ 11)

itz*_*aki 7 c++ initialization c++11 enum-class stdarray

我在C++ 11中有以下类:

class MyTable
{
    public:
    enum class EntryType
    {
        USED, FREE
    };

    MyTable(EntryType value)
    {
        for (uint32_t i = 0; i < 10; ++i)
        {
            memset(_table[i].data(), (int)value, sizeof(_table[0][0]) * 50);
        }
    }
    array<array<EntryType, 50>, 10> _table;
}
Run Code Online (Sandbox Code Playgroud)

尝试使用EntryType :: FREE的值构造MyTable的对象,二维数组中的每个项的值都为0x01010101(每8位1b),而不是仅为0x1的预期值

我猜它与我的value被投入有关int,但我不知道为了解决这个问题我应该做些什么.

gsa*_*ras 6

memset() 预计会以这种方式工作,因为它是

将目标缓冲区的每个字节设置为指定的值.

阅读更多内容为什么memset()错误地初始化int?

但是,要小心,因为正如juanchopanza所说,最后std::array可能有填充(在std :: array alignment中读取更多 ),这意味着这种方法可能会失败.


由于它是一个2D数组,你可以使用基于范围的for循环std::array::fill,如下所示:

for(auto& row : _table)
    row.fill(value);
Run Code Online (Sandbox Code Playgroud)

正如renzo所述.

如果您不想将每一行设置为相同的值,您可以这样做:

for(auto &row : array)
    for(auto &col : row)
         col = value; 
Run Code Online (Sandbox Code Playgroud)

基于范围的多维数组中阅读更多内容.