Fastest way to find out if all elements of a vector are false or true C ++?
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 to share
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 to share