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

元气小坏坏 提交于 2019-12-22 01:24:56

问题


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 close.


回答1:


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



回答2:


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.




回答3:


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.




回答4:


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();


来源:https://stackoverflow.com/questions/6506659/is-there-anything-like-stdand-or-stdor

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