Update dynamic_bitset with integer value

343 Views Asked by At

With dynamic_bitset it is possible to initialise based on an integer value (5, 124 below). Are updates with integer values also possible?

The solution below allocates heap memory on every update when creating a new dynamic_bitset. This is a poor solution (slow, possible heap fragmentation etc.).

    std::vector<boost::dynamic_bitset<uint8_t>> data;
    data.push_back(boost::dynamic_bitset<uint8_t>(4, 5));
    data.push_back(boost::dynamic_bitset<uint8_t>(7, 124));

    for(const auto& s: data)
        std::cout << s << std::endl; 

    for(int i; i<10; i++)
    {
      data[0]=boost::dynamic_bitset<uint8_t>(4, i);

      for(const auto& s: data)
          std::cout << s << std::endl; 
    }

Any ideas on how to update the value from an int without setting each individual bit?

1

There are 1 best solutions below

3
On

Perhaps you can init from a block list:

for(uint8_t i = 0; i<10; i++) {
    data[0].clear();
    data[0].init_from_block_range(&i, &i+1);
}

However, since it seems to assert that the bitset be clear before init, it would feel more natural to use append() with the same effect (and possible more benefits when you need > 8 bits eventually):

Live On Coliru

#include <boost/dynamic_bitset.hpp>
#include <iostream>
using BSet = boost::dynamic_bitset<uint8_t>;
using Block = BSet::block_type;

int main() {
    std::vector<BSet> data;
    data.emplace_back(4, 5);
    data.emplace_back(7, 124);

    auto& a = data[0];
    auto& b = data[1];

    std::cout << a << "\t" << b << "\n----\n";

    for(Block i = 0; i<10; i++)
    {
        a.clear();
        a.init_from_block_range(&i, &i+1);

        b.clear();
        b.append(i);

        std::cout << a << "\t" << b << "\n";
    }
}

Prints

0101    1111100
----
00000000    00000000
00000001    00000001
00000010    00000010
00000011    00000011
00000100    00000100
00000101    00000101
00000110    00000110
00000111    00000111
00001000    00001000
00001001    00001001

Note add .resize(4) to limit the capacity

I'm not sure whether this function should have been part of the public interface (it looks like it might not), but you apparently can use

    c.clear();
    c.dispatch_init(4, i, {});

See it Live On Coliru as well