Vector of bools

How would you make a template function that iterate through a container and set the elements with a given value?

And how do we call it?

And that’s it, right? Let’s use a vector of bool now.

Wait, it doesn’t compile.

It seems that using a forward_list or a deque of bools compiles properly..so this is specific to vector of bools.

Let’s try to use the data as rvalue.

Ok, it works now. It seems that the logic does not compile for proxy objects or rvalue sources, which is the case for bool type.

That’s a bit surprising, because all we did was a simple iteration through a container. Keep that in mind when using vector of bools.

But why?

Well, due to efficiency purposes, the implementation is using bits to store bools, but there’s no such type, so it uses chars instead…and you cannot access the individual bools other than using the reference member type.

What reference member type? well, the STL have a specialization for vector of bools 🙂

For alternatives, you can use std::bitset (for static size) or boost::dynamic_bitset (for dynamic size).

You may also like...