Look at how it is implemented. the STL builds vastly on templates and therefore the headers do contain the code they do.
for instance look at the stdc++ implementation here.
also interesting even though not an stl conforming bit vector is the llvm::BitVector from here.
the essence of the llvm::BitVector
is a nested class called reference
and suitable operator overloading to make the BitVector
behaves similar to vector
with some limitations. The code below is a simplified interface to show how BitVector hides a class called reference
to make the real implementation almost behave like a real array of bool without using 1 byte for each value.
class BitVector {
public:
class reference {
reference &operator=(reference t);
reference& operator=(bool t);
operator bool() const;
};
reference operator[](unsigned Idx);
bool operator[](unsigned Idx) const;
};
this code here has the nice properties:
BitVector b(10, false); // size 10, default false
BitVector::reference &x = b[5]; // that's what really happens
bool y = b[5]; // implicitly converted to bool
assert(b[5] == false); // converted to bool
assert(b[6] == b[7]); // bool operator==(const reference &, const reference &);
b[5] = true; // assignment on reference
assert(b[5] == true); // and actually it does work.
This code actually has a flaw, try to run:
std::for_each(&b[5], &b[6], some_func); // address of reference not an iterator
will not work because assert( (&b[5] - &b[3]) == (5 - 3) );
will fail (within llvm::BitVector
)
this is the very simple llvm version. std::vector<bool>
has also working iterators in it.
thus the call for(auto i = b.begin(), e = b.end(); i != e; ++i)
will work. and also std::vector<bool>::const_iterator
.
However there are still limitations in std::vector<bool>
that makes it behave differently in some cases.
std::vector<bool>
shouldn't compile. I also remember it's a specialization. – Winobool
, since the element doesn't have its own address. – Universalitystd::vector<bool> v;
will compile.&v[0]
will not (taking address of a temporary). – Gracklebool
and thus keeps reasonable behaviour. – Clearlyvector<bool>
has a bad rep but not entirely justifiably so: isocpp.org/blog/2012/11/on-vectorbool – Crimsonbool[]
arrays aren't packed with 1 bit per bool likevector<bool>
is. – Dougbool
type doesn't have standardized implementation, you can't rely on any particular feature of it (in standard portable C++ source), except using it asbool
, that should work, and that also works withvector<bool>
well. Its size is undefined and thevector<bool>
just takes this to another level (no address), to gain particular benefit of size optimization. Recommending general "avoid" is like: "bloat your SW". – Marketingvector<bool>
or C++ standard libraryvector<bool>
? – Ardene