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

11,127

Solution 1

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

Solution 2

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.

Share:
11,127
vincentleest
Author by

vincentleest

Updated on June 04, 2022

Comments

  • vincentleest
    vincentleest almost 2 years

    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?

  • vincentleest
    vincentleest about 10 years
    what if i want to set all of them to 1 instead of 0? do i do std::bitset<64> map[100] = {1}; ?
  • R Sahu
    R Sahu about 10 years
    @vincentleest that sets only map[0][0] to 1. The rest are set to 0.
  • Alexandru Barbarosie
    Alexandru Barbarosie about 10 years
    Hm, since the default constructor does the job, why do it twice? It takes time.
  • Brian Rodriguez
    Brian Rodriguez over 8 years
    Could also use std::fill(std::begin(map), std::end(map), -1);