Range-for-loops and std::vector<bool>
Because std::vector<bool>
is not a container !
std::vector<T>
's iterators usually dereference to a T&
, which you can bind to your own auto&
.
std::vector<bool>
, however, packs its bool
s together inside integers, so you need a proxy to do the bit-masking when accessing them. Thus, its iterators return a Proxy
.
And since the returned Proxy
is an prvalue (a temporary), it cannot bind to an lvalue reference such as auto&
.
The solution : use auto&&
, which will correctly collapse into an lvalue reference if given one, or bind and maintain the temporary alive if it's given a proxy.
std::vector<bool>
does not obey the standard container rules.
In particular, its operator[]
does not return bool&
.
The loop in the invalid code
#include <vector>
#include <iostream>
int main() {
std::vector<bool> boolVector(10);
for (auto& i: boolVector)
std::cout << i;
}
can be rewritten in any of three ways to iterate through the values:
-
(read-only)
for (auto i: boolVector) std::cout << i;
-
(read-only, possibly inefficient)
for (auto const& i: boolVector) std::cout << i;
-
(read/write)
for (auto&& i: boolVector) std::cout << i;
The choice between the first and last is down to whether you need to modify the values in the vector, or just to read them.
vector<bool>
is (usually) specialized explicitly to store each bool
in a single bit, reducing the storage costs from one byte per value to one byte per eight values. No processor I know of offhand is bit addressable, so it's impossible to store a reference to the values in the vector<bool>
. You need to use plain auto
, not auto&
for the iteration value i
.