1.
One does not simply ... iterate over items without iterating over them.
1 2 3 4 5 6 7
|
// foo is something suitable
auto it = std::find_if( List.begin(), List.end(), foo );
while ( List.end() != it ) {
// use the it
it = std::find_if( it+1, List.end(), foo ); // find next
}
|
However, the header algorithm has more than just find and find_if:
http://www.cplusplus.com/reference/algorithm/copy_if/
It is a loop!
1 2 3
|
std::vector<Person> fools;
fools.reserve( List.size() );
std::copy_if( List.begin(), List.end(), fools.begin(), foo );
|
2. Look at the equivalent of find_if:
1 2 3 4 5 6 7 8 9
|
template<class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if ( pred( *first ) ) return first;
++first;
}
return last;
}
|
- The 'first' is an iterator. (List.begin() is an iterator.)
- The 'pred' is used like it would be a function: name 'pred', a '(', some argument, and ')' -- that is a function call
- The "some argument" is '*first'. unary operator* on iterator is like dereferencing pointer. You access te pointed to object.
- The 'pred()' is used as a conditional expression. It returns bool, or something that can convert to bool.
So what is pred? As a template it can be any type that fulfills the requirements: can be called like a function with one argument (that has iterator's value_type) and returns a bool.
The term "predicate" mean something that returns bool. More generic terms are "functor", "function object" and "function pointer". Predicate is a special type of functor.
In
http://www.cplusplus.com/reference/algorithm/sort/
you see both function and struct used as "comp". A class/struct can have operator() so that an object can be used like it were a function. Such object can be "stateful", for example keep count of how many times the op() is called.
The
[]( /*args*/ ){ /*body*/ }
is indeed an unnamed function. The syntax is for a "lambda function" that was added in C++11. You can probably find more info about it.
Lambda syntax lets you write the function's code where it is used. You can immediately see what
42 == p.Age
is seeking without scrolling up / to other file to see what "myfunction" does. Lambda is an exception to the rule that one cannot define a function inside other function.
Lambda can be "stateful".