检查数组中的所有布尔值是否为真
Check if all boolean values in an array is true?
假设我有这个布尔数组:
bool something[4] = {false, false, false, false};
现在,有没有简单的方法来检查这个数组中的所有值是否一次为真/假?
而不是像这样做:
if(something[0] == false && something[1] == false..)
dothis();
使用 std::all_of
#include<algorithm>
...
if (std::all_of(
std::begin(something),
std::end(something),
[](bool i)
{
return i; // or return !i ;
}
)) {
std::cout << "All numbers are truen";
}
您可以通过求和来做到这一点:
#include <numeric>
int sum = std::accumulate(bool_array, bool_array + 4, 0);
if(sum == 4) /* all true */;
if(sum == 0) /* all false */;
这样做的优点是可以在一次传递中找到两个条件,而all_of
的解决方案则需要两个条件。
使用 for 循环。
allTrue = true;
allFalse = true;
for(int i=0;i<something.size();i++){
if(something[i]) //a value is true
allFalse = false; //not all values in array are false
else //a value is false
allTrue = false; //not all values in array are true
}
我的语法可能有点不对劲(有一段时间没有使用C++了),但这是通用的伪代码。
您可以搜索第一个假标志:
bool something[n];
...
bool allTrue = (std::end(something) == std::find(std::begin(something),
std::end(something),
false) );
相关文章:
- 检查类是否具有模板专用化(使用布尔值或 int 等模板参数)
- 布尔值是否需要在C++中表示为真时设置为 1 位/假时设置为 0 位
- 如何检查 C++ 中是否存在布尔值
- 是否应在分配时将布尔值截断为 true 或 false
- 将布尔值或浮点数分配给int32_t是否安全?
- 在一个作用域中推送五个对象指针,然后检查对象的布尔值是否为 false,会给出错误
- 编译器中的布尔值为 8 位.对它们的操作是否效率低下
- 特征稀疏布尔矩阵是否存储非零值
- 在命令行程序中使用布尔值。找不到定义标志并检查它们是否在参数中的方法
- 是否存在简单的指向布尔值作为线程取消标志的现实情况,无法有效地取消线程?
- x&=y 是否等同于 x = x &&y 如果两者都是 c++ 布尔值
- 是否有任何理由在C 中使用布尔值的枚举,而不是已经存在的布尔
- 检查数组中的所有布尔值是否为真
- 对布尔值使用逐位not运算符(~)是否会调用Undefined Behavior
- 如何在c++中检查布尔值是否未初始化
- 在比较过程中C++布尔值是否转换为整数
- 移动后是否应该 std::function::运算符布尔值返回 false
- 检查布尔值是否在混合 C/C++ 中定义
- C++编译器是否可以在内部用 0 或 1 以外的内容表示布尔值
- 在线程间的控制流中使用不带互斥锁的非原子布尔值是否安全?