Question

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?

Was it helpful?

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

OTHER TIPS

The default constructor of bitset initializes all elements to 0. I would say the best way of initializing an array is with

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

as that default initiates all elements. It is also clean, clear and concise.

Also, in your code you could think that a 0 is a 1, and viceversa (only changing the logic). But only if you are able to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top