I just watched this lecture about STLs by STL.
Around 57 minutes into the lecture, we have this code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
std::vector<std::string> v;
v.push_back("cat");
v.push_back("antelope");
v.push_back("puppy");
v.push_back("bear");
std::sort(v.begin(), v.end(),
[](const std::string& left, const std::string& right)
{
return left.size() < right.size();
}
);
for (std::vector<std::string>::iterator i = v.begin(); i != v.end(); ++i)
{
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
As expected, this prints the strings in the vector in increasing order of their lengths. My question is about the lambda expression which is the 3rd argument to the sort function. Internally, what gets passed to the input parameters 'left' & 'right'?
I added the line:
std::cout << "left: " << left << ", right: " << right << std::endl;
inside the body of the lambda, and the output I got was:
left: antelope, right: cat
left: antelope, right: cat
left: puppy, right: cat
left: puppy, right: antelope
left: puppy, right: cat
left: bear, right: cat
left: bear, right: antelope
left: bear, right: puppy
left: bear, right: cat
cat bear puppy antelope
So it looks like the 'left' and 'right' arguments are somehow related to the internal sorting algorithm in play. Can anyone shed more light on what exactly is going on?
My understanding is that if the lambda were to be a unary function, then it's input argument would have been whatever the iterator is currently pointing to. Is this correct?
But with a binary function, the input arguments puzzle me.