Search code examples
c++arraysc++11bitset

Initialize an array of std::bitset in C++


I'm trying to set all the elements in a 64-bit bitset array to 0. std::bitset<64> map[100]; I know i can use a loop to iterate all the elements and call .unset() on them like this.

int i;
for( i = 0; i< 100 ; i++){
    map[i].unset();
}

However, I want to know if there is a "proper" way of doing it.

Is std::bitset<64> map[100] = {}; okay?


Solution

  • The std::bitset default constructor initializes all bits to zero, so you don't need to do anything extra other than declare the array.

    std::bitset<64> map[100];  // each bitset has all 64 bits set to 0
    

    To set all bits to one, I'd use the bitset::set member function, which has an overload that sets all bits to one. Combine this with a for_each to call the member function on each array element.

    std::for_each(std::begin(map), std::end(map), 
                  [](std::bitset<64>& m) { m.set(); });
    

    Live demo

    Another solution is to initialize each array member, but this is rather tedious for a 100 element array;.

    std::bitset<64> map[100] = {0xFFFFFFFFFFFFFFFFULL, ... 99 times more};