C++11 introduced any_of
to algorithm
s.
This seems to work exactly like find_if
.
Say I have a functor: function<bool(int)> foo;
And an array: vector<int> bar;
It seems like these two calls do the exact same thing:
any_of(bar.begin(), bar.end(), foo);
and
bar.end() != find_if(bar.begin(), bar.end(), foo);
I further feel that all_of
, and none_of
can be accomplished by negating the find_if
statement.
Are these algorithms just here to do the comparison to end
for us, or is there a usefulness I don't understand?
std :: find_ifReturns an iterator to the first element in the range [first, last) for which pred(Unary Function) returns true. If no such element is found, the function returns last.
The any_of() function returns a Boolean value true if any of the elements present in the array or vector in the specified range satisfy the condition; otherwise, it returns false .
C++ Algorithm Library - find() Function The C++ function std::algorithm::find() finds the first occurrence of the element. It uses operator = for comparison.
I believe you're right that they are just more convenient interfaces to functionality that can be achieved in other ways.
The proposal to add them to the standard (N2666) says:
These three algorithms provide the ordinary mathematical operations ∀, ∃, and ∄: given a range and a predicate, determine whether that predicate is true for all elements; whether there exists an element for which the predicate is true; or whether there exist no elements for which the predicate is true. Strictly speaking there is no need to provide all three of these algorithms (
!none_of
andany_of
are equivalent), but all three of these operations feel equally fundamental.
The names are more natural and easier to read (certainly for non-expert C++ programmers) than an expression involving find_if
and an (in)equality.
GCC's standard library implements them by simply calling other functions:
all_of(first, last, pred)
is return last == std::find_if_not(first, last, pred);
none_of(first, last, pred)
is return last == std::find_if(first, last, pred);
any_of(first, last, pred)
is return !none_of(first, last, pred);
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