给定一个布尔值容器(例如std::vector<bool>
),是否有一种标准函数可以返回true
,如果所有值都为true
(“和”),或者如果至少一个值为true
则返回true
(“或”),并进行短路计算?
我今天早上查看了www.cplusplus.com,但没有找到类似的函数。
给定一个布尔值容器(例如std::vector<bool>
),是否有一种标准函数可以返回true
,如果所有值都为true
(“和”),或者如果至少一个值为true
则返回true
(“或”),并进行短路计算?
我今天早上查看了www.cplusplus.com,但没有找到类似的函数。
是否有一个标准函数,如果所有值为true("and"),则返回true
std::all_of(vec.begin(), vec.end(), [](bool x) { return x; } )
或者在至少一个值为真时返回true("或")。std::any_of(vec.begin(), vec.end(), [](bool x) { return x; } )
使用短路求值吗?
我只是在 lambda 中插入了打印语句,是的,两个函数都执行了短路求值。
std::find(vector.begin(), vector.end(), false) == vector.end() // all the values are true
或者:
std::find(vector.begin(), vector.end(), true) != vector.end() //at least one value is true
find_if
。非常感谢! - ereOnlogical_and
和 logical_or
与 reduction 结合使用来实现这一点。 accumulate
计算 reduction,因此: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::accumulate
用于归约,怎么样? - ltjax如果您不需要针对不同容器类型的通用算法...
由于您正在寻找短路评估,您可以尝试使用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();
<algorithm>
和<functional>
,其中有许多方便的函数和类,它们的实现是微不足道的。 - Konrad Rudolphstd::string
,因为他知道如何自己实现它们。当然,他确实知道,但结果是他的代码经常难以维护,并且充斥着琐碎的技巧。 - ereOnmemcpy
或std :: copy
吗?毕竟,这只是一个单独的for
循环。 - ereOnstd::all_of
和std::any_of
函数,所以肯定有很多人“像我一样”。此外,如果这些简单的函数可以进行内联(它们肯定可以),那么与“编写自己版本的这些函数”相比,它们会带来什么样的大小差异呢? - ereOn