Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any_of Versus find_if

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?

like image 406
Jonathan Mee Avatar asked Dec 11 '14 15:12

Jonathan Mee


People also ask

What is std :: Find_if?

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.

What does any_ of do in c++?

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 .

What library is std :: find in?

C++ Algorithm Library - find() Function The C++ function std::algorithm::find() finds the first occurrence of the element. It uses operator = for comparison.


1 Answers

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

like image 95
Jonathan Wakely Avatar answered Sep 28 '22 08:09

Jonathan Wakely