Search code examples
c++arrayscontrol-flow

Quitting a function if all values in an array are true


There is a simple feature I would like to add to one of the members of a class: I would like to quit the function in case all the values of some boolean (2d) array are true.

In the simpler case of a 1d array I can do it this way:

int SIZE = 10;
std::vector<bool> myArray(SIZE, true);
int i = 0;
while(myArray[i] and i < SIZE){
    ++i;
    }
if(i == SIZE){
    return;
    }
// rest of the code for array not all true

There is probably no quicker way to do it (minus marginal optimizations) but I find it a bit ugly. Are there nicer ways to do it?

=========================================

In the end I decided to implement:

{
bool allTrue = true;
for(int i = 0; i < SIZE1 and allTrue; ++i)
    for(int j = 0; j < SIZE2 and allTrue; ++j)
        allTrue &= myArray[i][j];
if(allTrue)
    return;
}

Solution

  • You may use std::all_of from <algorithm>:

    if (std::all_of(myArray.begin(), myArray.end(), [](bool b) {return b;})) {
        return;
    }