Check if all boolean values in an array is true?

Use 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 true\n";
}

Use a for loop.

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
}

My syntax might be a bit off (haven't used C++ in a while) but this is the general pseudocode.


You can do this by summing:

#include <numeric> 

int sum = std::accumulate(bool_array, bool_array + 4, 0);
if(sum == 4) /* all true */;
if(sum == 0) /* all false */;

This has the advantage of finding both conditions in one pass, unlike the solution with all_of which would require two.

Tags:

C++

Arrays