Why std :: min_element and a non-std :: vector <bool> company
I have an instance std::vector<bool>
( foo
say) and I need to write a function that returns true
if all elements are true
.
I use
return *std::min_element(foo.begin(), foo.end());
for this, but it got me thinking: you know what the minimum element false
is if the container contains at least one value false
. In other words, you do not need to go through the entire container before end()
, which means that the specialization std::min_element
is suitable, just as the specialization std::vector<bool>
is considered suitable.
Did I miss something? Or would it be considered a premature optimization? Perhaps a good compiler would parse it anyway.
source to share
There is no need to specialize std::min_element
for std::vector<bool>
. To get the functionality you want, you can simply use std::any_of
that will stop on first occurrence.
return !std::any_of(foo.begin(), foo.end(), [](auto i){return i == false;});
If we change this to std::all_of
like Some programmer dude , then you don't have to deny the return value that gives you
return std::all_of(foo.begin(), foo.end(), [](auto i){return i;});
It's a little cleaner and clearer.
source to share
Suggestion: use std::any_of
which:
Returns true if pred returns true for any of the elements in the range [first, last) and false otherwise.
means it will return as soon as it finds it false
.
Example:
// any_of example
#include <iostream>
#include <algorithm> // std::any_of
#include <vector>
int main () {
std::vector<bool> foo = {true, true, true};
if ( !std::any_of(foo.begin(), foo.end(), [](bool i){return i == false;}) )
std::cout << "All elements are true\n";
return 0;
}
Output:
All elements are true.
Since you don't have an assigned data-structure in place, then you std::min_element
should iterate over the entire vector as this is a generic method.
Specialization can do what you say, where you can take advantage of the functionality compare
it provides.
source to share