5

As we all probably know the C++ 98 vector<bool> specialization stores boolean values as bits rather than as bool variables. vector<bool>'s elements aren't addressable because C++ doesn't have pointers and references to bits, is there a workaround to this, any obvious pitfalls (that i seem to be oblivious to) and is it practical to even try and do so?

iKlsR
  • 2,642
  • 6
  • 27
  • 45

2 Answers2

2

vector<bool>'s elements are addressable as any other vector's elements e.g. with operator []. However, the operations will be slower, because of the memory compression.

Maybe faster implementation will use your own inmemory implementation and use binary shifts to address specific boolean value.

Also an alternative will be to use simple array in places where this is appropriate. Remember that you can allocate it dynamically using the new operator.

EDIT Alternative implementations might be found e.g. in this thread.

Community
  • 1
  • 1
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • you listed one pitfall as it being slower and alternative(s), i know of alternatives, i'm just trying to see if there is some way to work directly with it. I vaguely remember reading somewhere about a reference, this being a nested class of sorts but i can't seem to find anything on it. – iKlsR Dec 30 '12 at 14:26
  • @iKlsR you can work directly with it as I already pointed out in my answer. You can also look for alternative implementation e.g. here: http://stackoverflow.com/questions/670308/alternative-to-vectorbool – Boris Strandjev Dec 30 '12 at 14:29
  • i seem to be fumbling with my words, thanks for the additional links, what i'm thinking of is http://www.cplusplus.com/reference/vector/vector-bool/reference/ which would seem to work but i'm not sure how better than the (default [ ]) way it is. – iKlsR Dec 30 '12 at 14:34
  • @iKlsR what kind of operations are you interested in? – Boris Strandjev Dec 30 '12 at 14:39
  • it's in the question, iteration and referencing, don't get me wrong, you have provided an answer, it's just not 'satisfying' enough ;) . I feel there is a special way to do this, im just not asking properly i guess. – iKlsR Dec 30 '12 at 14:41
  • 1
    You *can* iterate and you *can* use `std::vector::reference` as a "proxy" reference. See http://liveworkspace.org/code/1gNZ5O$0 for an example. – johnsyweb Dec 30 '12 at 14:44
  • @iKlsR: while iterating, won't you need to also access the value in some way that will allow you to use it in some operations? Most such cases require you to cast to `bool` – Boris Strandjev Dec 30 '12 at 14:56
  • @Boris yes and yes, even tho in this case the raw bits are a tad bit more useful. Thanks for the help. – iKlsR Dec 30 '12 at 15:00
1

Instead of references/pointers to bits, vector<bool> uses wrapper objects with overloaded operators that behave (in most cases) like references/pointers to booleans.

sth
  • 222,467
  • 53
  • 283
  • 367