Lambda creation
I think I had the same confusion when I first saw lambdas.
So let's see what this expression means:
[](auto x, auto y) {return(y < x); }
This just creates the lambda object. It does not call the labda. Think of it as a class definition + object creation.
Your questions
Let's consider the declaration of sort
:
template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
and your call to it
sort(ivec.begin(), ivec.end(), [](auto x, auto y) { return(y < x); });
when the above line of code is being executed?
I'll interpret this as "when is the body of the lambda executed?"
Whenever sort
calls it. What you need to understand: sort
receives a parameter named comp
that is callable. This parameter can be of type: pointer to function or a callable type (i.e. a type with operator()
defined). A lambda is a special case of a callable type. When you call sort
you just pass this object to the sort
function. Now sort
has an object (comp
) that it can call whenever it wants/needs.
what is being passed in the parameter list as parameter?
Whatever sort
passes as arguments when it calls comp
. It the case of std::sort
it will call it with pairs of elements from the range with the purpose of determining if those two elements are already sorted between them or not.
Example
The easiest is to just see it in action. For this lets consider the simplest sorting algorithm: a dumb bubble sort:
template< class RandomIt, class Compare >
void bubble_sort( RandomIt first, RandomIt last, Compare comp )
{
for (auto left = first; left != last; ++left)
{
for (auto right = std::next(left); right != last; ++right)
{
if (!comp(*left, *right))
{
std::swap(*left, *right);
}
}
}
}
the algorithm is for exposition only
As you can see bubble_sort
makes calls to comp
by passing arguments. Like std::sort
the arguments passed are pairs of elements from the [first, last)
range.