检查数组中的所有布尔值是否为真

Check if all boolean values in an array is true?

本文关键字:布尔值 是否 数组 检查      更新时间:2023-10-16

假设我有这个布尔数组:

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) );