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();
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";
}
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.
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 could search for the first false flag:
bool something[n];
...
bool allTrue = (std::end(something) == std::find(std::begin(something),
std::end(something),
false) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With