I have a std::vector<bool> instance (foo, say), and I need to write a function that returns true if all the elements are true.
I use
return *std::min_element(foo.begin(), foo.end());
to achieve that, but this has got me thinking: you know the minimum element is false, if the container contains at least one false value. In other words, you don't need to traverse the whole container to end(), which means that a specialisation of std::min_element is appropriate, just like a specialisation of std::vector<bool> has been deemed appropriate.
Am I missing anything? Or would this be viewed as a premature optimization? Perhaps a good compiler would sort it out anyway.
There is no need to specialize std::min_element for std::vector<bool>. To get the functionality that you want you can just use std::any_of which will stop at the first occurrence.
return !std::any_of(foo.begin(), foo.end(), [](auto e){ return e == false; });
If we change this to std::all_of as Some programmer dude suggests then you do not need to negate the return value, which gives you
return std::all_of(foo.begin(), foo.end(), [](auto e){ return e; });
Which is a little cleaner and easier to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With