给定一个布尔值容器(例如std::vector<bool>
),如果所有值都是true
("and"),是否有标准函数返回true
;如果至少有一个值是true
("or"),则返回true
,并进行短路评估?
今天早上我浏览了www.cplusplus.com,但找不到任何接近的东西。
如果所有值都为true("and"),是否有返回true的标准函数
std::all_of(vec.begin(), vec.end(), [](bool x) { return x; } )
如果至少有一个值为真("或"),则为真
std::any_of(vec.begin(), vec.end(), [](bool x) { return x; } )
短路评估?
我刚刚在lambda中插入了print语句,是的,这两个函数都执行短路。
您可以通过以下方式实现:
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
您可以将函数对象logical_and
和logical_or
与归约一起使用来实现这一点。
CCD_ 8计算减少量。因此:
bool any = std::accumulate(foo.begin(), foo.end(), false, std::logical_or<>());
bool all = std::accumulate(foo.begin(), foo.end(), true, std::logical_and<>());
注意:这是而不是使用短路(accumulate
函数对短路一无所知,即使函数知道),而Igor的聪明解决方案是。
如果您不需要针对不同容器类型的通用算法。。。
当您正在寻找短路评估时,您可能会给std::valarray一个机会。对于and
使用valarray::min() == true
对于or
,您可以使用Igor提到的std::find
。
如果您知道编译时要存储的元素数量,您甚至可以使用std::bitset:
bitset<100> container();
//... fill bitset
bool or = container.any();
bool and = container.count() == container.size();