Fastest way to find out if all elements of a vector are false or true C ++?

I was wondering if there was a quick way to find out if all elements in a vector are false or true ? How, instead of checking each item with a loop?

+3


source to share


5 answers


I would like to use new algorithms for clarity:

// all true
std::all_of(vec.begin(), vec.end(), [](bool v) { return v; });

// all false
std::all_of(vec.begin(), vec.end(), [](bool v) { return !v; });
std::none_of(vec.begin(), vec.end(), [](bool v) { return v; });

      



You cannot know if all the elements of a vector are true without actually checking each element of the vector. At best, you are revisiting memory differently and checking more than one item at a time, but you still need to check everything until you find one that fails the test.

+9


source


The easiest IMO is a free feature find



if (std::find(begin(v), end(v), true) == end(v)) // All false

      

+2


source


This requires a loop, but will at least use short-quoted behavior.

bool all = true;
std::vector<bool>::iterator it = myVec.begin();

while(all && it != myVec.end())  // Stops early if it hits a false
{
    all &= *it;
    ++it;
}

      

If all

- true

, all elements in the vector were true. If all

false, at least one item was not true

.

0


source


You can also use std::accumulate()

:

int sum = std::accumulate(std::begin(v), std::end(v), 0);

if (sum == v.size()) {
    // All true
}
else if (sum) {
    // Any true, any false
}
else {
    // All false
}

      

0


source


I think the most efficient would be:

if(v.find(v.begin(), v.end(), true) == v.end())
// All false  

if(v.find(v.begin(), v.end(), false) == v.end())
// All true

      

0


source







All Articles