ere*_*eOn 22 c++ algorithm boolean std short-circuiting
给定一个布尔值的容器(例如std::vector<bool>
),是否存在标准函数,true
如果所有值都是true
("和")或者true
至少有一个值是true
("或"),则返回短路评估?
今天早上我在www.cplusplus.com上挖了一个但是找不到任何东西.
fre*_*low 44
是否有一个标准函数,如果所有值都为真("和"),则返回true
std::all_of(vec.begin(), vec.end(), [](bool x) { return x; } )
Run Code Online (Sandbox Code Playgroud)
如果至少有一个值为真,则为true("或")
std::any_of(vec.begin(), vec.end(), [](bool x) { return x; } )
Run Code Online (Sandbox Code Playgroud)
短路评估?
我刚刚将print语句插入到lambda中,是的,两个函数都执行短路.
Igo*_*Oks 38
你可以实现:
和:
std::find(vector.begin(), vector.end(), false) == vector.end() // all the values are true
Run Code Online (Sandbox Code Playgroud)
要么:
std::find(vector.begin(), vector.end(), true) != vector.end() //at least one value is true
Run Code Online (Sandbox Code Playgroud)
Kon*_*lph 10
您可以使用函数对象logical_and
并logical_or
结合缩小来实现此目的.
accumulate
计算减少量.因此:
bool any = std::accumulate(foo.begin(), foo.end(), false, std::logical_or);
bool all = std::accumulate(foo.begin(), foo.end(), true, std::logical_and);
Run Code Online (Sandbox Code Playgroud)
警告:这不是使用短路(accumulate
即使算子也没有关于短路的功能),而Igor的聪明解决方案是.