I was wondering if there was a quick way to find out if all elements in a vector are false or true? Like instead of checking each element using a loop?
A simple solution to check if all elements of a vector are equal is using the std::adjacent_find function. It returns the first occurrence of adjacent elements that satisfies a binary predicate, or end of the range if no such pair is found.
Use the Vector. size method. It will tell you the number of elements in the vector.
Comparing two vectors using operator == std::vector provides an equality comparison operator==, it can be used to compare the contents of two vectors. For each element in the vector it will call operator == on the elements for comparisons.
I'd take advantage of the 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 can't find out if all the elements in a vector are true without actually checking every element of the vector. Best-case, you reinterpret the memory differently and check more than 1 element at a time, but you still have to check everything until you find one that fails your test.
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