Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a two-dimensional std::array of type enum class (C++11)

I have the following class in 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;
}

Trying to construct an object of MyTable with value of EntryType::FREE, every item in the 2-dimensional array has the value of 0x01010101 (1b every 8 bits), instead of the expected value of just 0x1

I'm guessing it has something to do with my value being casted to int, but I don't know what I'm supposed to do in order to fix it.

like image 698
itzhaki Avatar asked May 26 '17 09:05

itzhaki


People also ask

How do you initialize a two dimensional array in C++?

Initialization of two-dimensional array A better way to initialize this array with the same array elements is given below: int test[2][3] = { {2, 4, 5}, {9, 0, 19}}; This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements each.

What are the two ways to initialize a 2D array?

Two – Dimensional Arrays Like the one dimensional array, 2D arrays can be initialized in both the two ways; the compile time initialization and the run time initialization. int table-[2][3] = { { 0, 2, 5} { 1, 3, 0} };

Can C++ enum class have methods?

No, it cannot.


2 Answers

memset() is expected to work that way, since it's

sets each byte of the destination buffer to the specified value.

Read more in Why is memset() incorrectly initializing int?

However, be careful, since as juanchopanza said, std::array may have padding at the end (read more in std::array alignment ), which means that this approach might fail.


Since it's a 2D array, you could use a range-based-for loop and std::array::fill, like this:

for(auto& row : _table)
    row.fill(value);

as renzo stated.

In case you do not want to set every row at the same value, you could do it like this of course:

for(auto &row : array)
    for(auto &col : row)
         col = value; 

Read more in range-based for on multi-dimensional array.

like image 121
gsamaras Avatar answered Sep 24 '22 17:09

gsamaras


This can be done with a ranged-based for loop and the std::array::fill member function.

MyTable(EntryType value)
{
    for (auto& row : _table) {
        row.fill(value);
    }
}

This will continue to work even if you change the array dimensions.

like image 31
Blastfurnace Avatar answered Sep 22 '22 17:09

Blastfurnace