Lets do the beginner's "find largest element":
1 2 3 4 5 6 7
|
auto max = arr[0];
for ( size_t i = 1; i < N; ++i ) {
auto value = arr[i];
if ( max < value ) {
max = value;
}
}
|
Focus on line 4. There is an expression
max < value
as condition. That expression dictates what is largest.
The operator< is a function. A binary predicate function. Binary = takes two operands; predicate = returns
bool
.
The operator syntax (
operand operator operand) is convenient. but function syntax is also allowed:
operator< ( max, value )
If we are using a function in the expression, we could have used some other suitable function instead:
pred( max, value )
The 'pred' has to accept two arguments and return a bool.
In the example in your post there is 'myfn' that meets that criteria.
The global variable 'myobj' is of type myclass. myclass has operator() that allows myobj to be used like pred is used.
The possibility to replace the expression in the condition makes the three argument version of max_element much more generic. You can redefine what you mean by "larger".
Take class Person. It can have many attributes. For example age and height.
We can write operator< for class Person, but how should it compare two persons? When is one more than other?
What if we don't care about absolute "moreness" and want the tallest person? Or the youngest?
That is where the third parameter shines. We give min_element a pred that takes two persons and compares age.