Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all boolean values in an array is true?

Tags:

c++

arrays

Let's say I have this boolean array:

bool something[4] = {false, false, false, false};

Now, is there any simple way to check if all the values in this array is true/false at once?

Instead of doing it like this:

if(something[0] == false && something[1] == false..)
dothis();
like image 919
Hummelmannen Avatar asked Dec 19 '13 17:12

Hummelmannen


4 Answers

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";
}
like image 112
P0W Avatar answered Oct 07 '22 16:10

P0W


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.

like image 20
Eric Avatar answered Oct 07 '22 17:10

Eric


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.

like image 41
Embattled Swag Avatar answered Oct 07 '22 16:10

Embattled Swag


You could search for the first false flag:

bool something[n];
...

bool allTrue = (std::end(something) == std::find(std::begin(something),
                                                 std::end(something),
                                                 false) );
like image 28
Den-Jason Avatar answered Oct 07 '22 16:10

Den-Jason