Is there anything like "std::and" or "std::or"?
Given a container of boolean values (An example is std::vector<bool>
), is there a standard function that returns true
if all the values are true
("and") or true
if at least one value is true
("or"), with short circuit evalutation ?
I digged trough www.cplusplus.com this morning but couldn't find anything clo开发者_如何学Gose.
is there a standard function that returns true if all the values are true ("and")
std::all_of(vec.begin(), vec.end(), [](bool x) { return x; } )
or true if at least one value is true ("or")
std::any_of(vec.begin(), vec.end(), [](bool x) { return x; } )
with short circuit evalutation?
I just inserted print statements into the lambda, and yes, both functions perform short-circuiting.
You can implement by:
AND:
std::find(vector.begin(), vector.end(), false) == vector.end() // all the values are true
OR:
std::find(vector.begin(), vector.end(), true) != vector.end() //at least one value is true
You can use the function objects logical_and
and logical_or
in conjunction with a reduction to accomplish that.
accumulate
calculates the reduction. Hence:
bool any = std::accumulate(foo.begin(), foo.end(), false, std::logical_or<>());
bool all = std::accumulate(foo.begin(), foo.end(), true, std::logical_and<>());
Caveat: this is not using short-circuiting (the accumulate
function knows nothing about short-circuiting even though the functors do), while Igor’s clever solution is.
If you do not need a generic algorithm for different container types...
As you are looking for short circuit evaluation, you may give std::valarray a chance. For and
use valarray::min() == true
for or
you could use std::find
as mentioned by Igor.
In case you know the number of elements to store at compile time, you could even use a std::bitset:
bitset<100> container();
//... fill bitset
bool or = container.any();
bool and = container.count() == container.size();
精彩评论