Lamdas in C++ are used in places where callback code would be needed so that you don't need to decouple a class or function.
Say you have a collection of structures. You want to find an element of the collection where one data field matches a given parameter. Say, a list of employees and you are looking for some SSN. You can write
Code:
struct Employee {
std::string name;
Department department;
std::string SSN;
/* ... */
};
void do_something_with(std::string SSN)
{
for (auto it = employees.begin(); it != employees.end(); ++it)
if (it->SSN == SSN)
break;
/* ... */
}
But recently, C++ has been on something of a crusade against loops. We've all written more than enough loops in our lives. Now, we could use std::find_if to find the wayward employee, but that requires a predicate. Which we can do like this:
Code:
class matchesSSN {
const std::string &SSN;
public:
explicit matchesSSN(const std::string &SSN) : SSN(SSN) = default;
bool operator()(const Employee& emp) { return emp.SSN == SSN; }
};
void do_something_with(std::string SSN)
{
auto it = std::find_if(employees.begin(), employees.end(), matchesSSN(SSN));
That is better, but it requires us to create a whole new class, just for a single purpose. Reuse of that class is going to be very limited. It is essentially boilerplate. However, with lambdas:
Code:
void do_something_with(std::string SSN)
{
auto it = std::find_if(employees.begin(), employees.end(), [SSN](const Employee& emp){ return emp.SSN == SSN; });
And boom, no more loop and no more temporary class with weird semantics.
You might not see the appeal with find_if, but make it remove_if and suddenly it is useful.
PeterX wrote:
Does one really need lambdas when you have functions?
Lamdas can capture. Functions cannot. You can create functors to make a function that captures some state, but for single-use items, this is typically less than ideal.
I would bring up the example of qsort(), where it is always a hassle to uncouple a comparator from the rest of the code, often just for a single use, and how a capture-less lambda can be used there, but then, C++ has std::sort.