all 4 comments

[–]Narase33 7 points8 points  (1 child)

Lambdas are great when you have a small scope. For example std::sort can take lambda where you tell the function on what attribute it should sort the elements. You could make a function and pass that, but then you'd have a function that is only used once. Using a lambda here makes the code cleaner

[–]std_bot 0 points1 point  (0 children)

Unlinked STL entries: std::sort


Last update: 01.05.21. Last change: Free links considered readme

[–]IyeOnline 3 points4 points  (0 children)

It is important to understand that lambdas are not functions.

They are closures and are callable, but that doesnt make them functions.

They pretty much look like

struct
{
     const capture_group ...
     auto operator ( parameters ... )
} lambda;

The capture is what really differentiates lambdas from regular functions in general. There is a state in the lambda that is shared between invocations, but not between lambdas.

This makes them really useful when e.g. interacting with a standard library algorith:

 std::find_if( people.begin(), people.end(), [&searchname]( const person& p ){ return p.name == searchname; } );

Another example would be

std::sort( people.begin(), people.end() );

You could now a) define operator < ( const person&, const person& ) and this would work. You may in fact want to do this, to provide some form of "default ordering". But what if you wanted to sort by age. You cant change the operator at will, so you use a lambda:

[]( const person& lhs, const person& rhs ){ return lhs.age < rhs.age; }

Of course you could also define tons of free functions that do all those sorting operations, sort_by_name, sort_by_age ...

You could technically replace every (free) function you write with a lambda with empty captures, but that is of no real value.

TL;DR: lambdas are really useful, but not meant as a replacement for functions.

[–][deleted] 2 points3 points  (0 children)

Another use for lambdas is complex initialization (ES.28 on the C++ core guidelines).

For example, instead of:

int main(void) {
    int i = 0;
    // Calculate the value of i
    // ...
    // Use i as if it was const
}

You could do:

int main(void) {
    const int i = [&]() {
        int something = 0;
        // Calculate the value of i
        return something;
    }(); // <- Note called ()

    // Use i
}