0

I'm writing a program that is supposed to manipulate very long strings of boolean values. I was originally storing them as a dynamic array of unsigned long long int variables and running C-style bitwise operations on them.

However, I don't want the overhead that comes with having to iterate over an array even if the processor is doing it at the machine code level - i.e. it is my belief that the compiler is probably more efficient than I am.

So, I'm wondering if there's a way to store them as a bitfield. The only problem with that is that I heard you needed to declare a constant at runtime for that to work and I don't particularly care to do that as I don't know how many bits I need when the program starts. Is there a way to do this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Woody1193
  • 7,252
  • 5
  • 40
  • 90
  • 6
    Have you looked at `std::bitset` ? – a_pradhan Sep 14 '15 at 07:01
  • 6
    Or perhaps `std::vector`, depending on how you are going to "manipulate" them. – Bo Persson Sep 14 '15 at 07:08
  • 1
    And Boost has `dynamic_bitset`. Bitfields won't work; they do have to be constant width (and no bigger than a normal integral type, I think). – Alan Stokes Sep 14 '15 at 07:16
  • Exactly what "manipulation" are we talking of? – Mats Petersson Sep 14 '15 at 07:49
  • I hadn't heard of `std::bitset` I'll look into it. I'd rather not use `std::vector` as there could be in excess of a million bits and I don't want to allocate a byte to each one. I'd rather not use Boost if I can get away with it. As for manipulation, I'm talking about the usual C-style bitwise operators, <<, >>, |, &, ^, ~, etc – Woody1193 Sep 14 '15 at 08:34

1 Answers1

0

As per the comments, std::bitset or std::vector<bool> are probably what you need. bitset is fixed-length, vector<bool> is dynamic.

vector<bool> is a specialization of vector that only uses one bit per value, rather than sizeof(bool), like you might expect... While good for memory use, this exception is actually disliked by the standards body these days, because (among other things) vector<bool> doesn't fulfil the same contract that vector<T> does - it returns proxy objects instead of references, which wreaks havoc in generic code.

SteveL
  • 1,811
  • 1
  • 13
  • 23
Thief
  • 369
  • 1
  • 5