8

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();
2
  • 3
    Use a loop. Like in the duplicate above. Commented Dec 19, 2013 at 17:06
  • This question should not have been close, it is more specific than the alternative. Commented Dec 6, 2019 at 10:16

4 Answers 4

26

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";
}
Sign up to request clarification or add additional context in comments.

9 Comments

@Salgar Yeah, they are. bool is an integral type -> it's a number.
I understand that, he edited his answer. It was strange before.
It would be nice to remark that all_of is only defined from C++11 on...
Just wanted to add an approach with pointers: std::all_of(something, &something[4], [](bool b) {return b;});
|
8

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.

3 Comments

What about any array with millions bools and first one as false and need to check all true ? std::all_of just uses std::find_if_not
@P0W: I was assuming the question was to find both conditions, not either condition
Still you should not need to go through the whole array for either of the conditions if the first two elements are true and false respectively..
6

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.

Comments

6

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

2 Comments

How does this add to the accepted answer from seven years ago?
@DevSolar it's a different approach. Similar to std::all_of, but different nonetheless.. Plus it doesn't need a lambda.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.