2

the problem is this: I need to create a bitmap (a series of binary flags) to hold true/false information about a bunch of objects; the number of object is not known a priori so I have to allocate enough flags at runtime, possibly during the bitmap creation.

Given max_num_elements elements, my first idea was to allocate an array of ((num_elements/8)+1)*sizeof(char) bits: since a char is 8bit long it can handle 8 binary flags, so I get the minimun number of chars to hold num_elements flags, with a max memory waste of 7bits.

The real problem is for checking/setting the flags: I tought to do some bitshifting on the whole array followed by a bitwise and to get flag n like

flag_n = (flag_array>>n)&0d1

but if I understood correctly, the shifting operation won't afffect the whole array, just the first element.

How can I achieve this?

fudo
  • 2,254
  • 4
  • 22
  • 44
  • unless I'm missing something, why not a long instead of a bitmap. The first bit holds true/false for some property, the second bit for another property and so on. – Eugene Apr 04 '17 at 07:49

1 Answers1

1

std::vector<bool> is specialised to achieve exactly this.

It is actually a problem in many cases, since access to an element returns a proxy object rather than a bool&, so it doesn't quite behave like all the other containers, but it seems like in your case it suits what you need.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • Thank you very much @bobtfish, didn't know about this specialization, it will be very helpful. But reading the link i also found [std::bitset](http://en.cppreference.com/w/cpp/utility/bitset/bitset), that fits best my needs, so I'll go for it in my project. – fudo Apr 04 '17 at 08:11