Is there anything like “std::and” or “std::or”?

自作多情 提交于 2019-12-04 22:26:19

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

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 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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!