c++ - find_if - std::find lambda




any_of Versus find_if (2)

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 and any_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);

C++11 introduced any_of to algorithms.

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?


Please note the return type of the two algorithms. Just like binary_search only returns if the provided element can be found in a sorted sequence, while lower_bound returns an iterator to first element not smaller than the provided element,any_of and find_if complement each other. Note that binary_search is (almost) the same as !(val < lower_bound(a.begin(), a.end(), val))

any_of will only tell you if the predicate holds for any element, while find_if will return an iterator to the element that makes the predicate become true. Also note that find_if guarantees that an iterator to the first element that makes the predicate become true will be returned, while any_of does not have such restrictions. Thus in theory in some cases any_of can be more efficient.





find