有没有像"std :: and"或"std :: or"这样的东西?

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)

  • @ereOn:如果您有C++ 0x,建议使用.但是,我不会在关键生产代码中使用非标准功能.如果你想要一个标准的C++解决方案 - 顺便提一下,那个实际上适合你的解决方案 - 那么这就是目前所说的问题的正确答案.未来的标准使它更容易一个有趣的旁注. (2认同)

Kon*_*lph 10

您可以使用函数对象logical_andlogical_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的聪明解决方案是.

  • 这是使用短路评估规则吗? (3认同)