Search

10.15 — Introduction to lambdas (anonymous functions)

Consider this snippet of code that we introduced in lesson 9.25 -- Introduction to standard library algorithms:

This code searches through an array of strings looking for the first element that contains the substring “nut”. Thus, it produces the result:

Found walnut

And while it works, it could be improved.

The root of the issue here is that std::find_if requires that we pass it a function pointer. Because of that, we are forced to define a function that’s only going to be used once, that must be given a name, and that must be put in the global scope (because functions can’t be nested!). The function is also so short, it’s almost easier to discern what it does from the one line of code than from the name and comments.

Lambdas to the rescue

A lambda expression (also called a lambda or closure) allows us to define an anonymous function inside another function. The nesting is important, as it allows us both to avoid namespace naming pollution, and to define the function as close to where it is used as possible (providing additional context).

The syntax for lambdas is one of the weirder things in C++, and takes a bit of getting used to. Lambdas take the form:

[ captureClause ] ( parameters ) -> returnType
{
    statements;
}

The capture clause and parameters can both be empty if they are not needed.

The return type is optional, and if omitted, auto will be assumed (thus using type inference used to determine the return type). While we previously noted that type inference for function return types should be avoided, in this context, it’s fine to use (because these functions are typically so trivial).

Also note that lambdas have no name, so we don’t need to provide one.

As an aside...

This means a trivial lambda definition looks like this:

Let’s rewrite the above example using a lambda:

This works just like the function pointer case, and produces an identical result:

Found walnut

Note how similar our lambda is to our containsNut function. They both have identical parameters and function bodies. The lambda has no capture clause (we’ll explain what a capture clause is in the next lesson) because it doesn’t need one. And we’ve omitted the trailing return type in the lambda (for conciseness), but since operator!= returns a bool, our lambda will return a bool too.

Type of a lambda

In the above example, we defined a lambda right where it was needed. This use of a lambda is sometimes called a function literal.

However, writing a lambda in the same line as it’s used can sometimes make code harder to read. Much like we can initialize a variable with a literal value (or a function pointer) for use later, we can also initialize a lambda variable with a lambda definition and then use it later. A named lambda along with a good function name can make code easier to read.

For example, in the following snippet, we’re using std::all_of to check if all elements of an array are even:

We can improve the readability of this as follows:

Note how well the last line reads: “return whether all of the elements in the array are even

But what is the type of lambda isEven?

As it turns out, lambdas don’t have a type that we can explicitly use. When we write a lambda, the compiler generates a unique type just for the lambda that is not exposed to us.

For advanced readers

In actuality, lambdas aren’t functions (which is part of how they avoid the limitation of C++ not supporting nested functions). They’re a special kind of object called a functor. Functors are objects that contain an overloaded operator() that make them callable like a function.

Although we don’t know the type of a lambda, there are several ways of storing a lambda for use post-definition. If the lambda has an empty capture clause, we can use a regular function pointer. In the next lesson, we introduce lambda captures, a function pointer won’t work anymore at that point. However, std::function can be used for lambdas even if they are capturing something.

The only way of using the lambda’s actual type is by means of auto. auto also has the benefit of having no overhead compared to std::function.

Unfortunately, we can’t always use auto. In cases where the actual lambda is unknown (e.g. because we’re passing a lambda to a function as a parameter and the caller determines what lambda will be passed in), we can’t use auto without compromises. In such cases, std::function can be used.

Output

0
1
2

If we had used auto for the type of fn, the caller of the function wouldn’t know what parameters and return type fn needs to have. Furthermore, functions with auto parameters cannot be separated into a header and source file. We cover the reason for this restriction when we talk about templates.

Rule

Use auto when initializing variables with lambdas, and std::function if you can’t initialize the variable with the lambda.

Generic lambdas

For the most part, lambda parameters work by the same rules as regular function parameters.

One notable exception is that since C++14 we’re allowed to use auto for parameters (note: in C++20, regular functions will be able to use auto for parameters too). When a lambda has one or more auto parameter, the compiler will infer what parameter types are needed from the calls to the lambda.

Because lambdas with one or more auto parameter can potentially work with a wide variety of types, they are called generic lambdas.

For advanced readers

When used in the context of a lambda, auto is just a shorthand for a template parameter.

Let’s take a look at a generic lambda:

Output:

June and July start with the same letter

In the above example, we use auto parameters to capture our strings by const reference. Because all string types allow access to their individual characters via operator[], we don’t need to care whether the user is passing in a std::string, C-style string, or something else. This allows us to write a lambda that could accept any of these, meaning if we change the type of months later, we won’t have to rewrite the lambda.

However, auto isn’t always the best choice. Consider:

Output:

There are 2 months with 5 letters

In this example, using auto would infer a type of const char*. C-style strings aren’t easy to work with (apart from using operator[]). In this case, we prefer to explicitly define the parameter as a std::string_view, which allows us to work with the underlying data much more easily (e.g. we can ask the string view for its length, even if the user passed in a C-style array).

Generic lambdas and static variables

One thing to be aware of is that a unique lambda will be generated for each different type that auto resolves to. The following example shows how one generic lambda turns into two distinct lambdas:

Output

0: hello
1: world
0: 1
1: 2
2: ding dong

In the above example, we define a lambda and then call it with two different parameters (a string literal parameter, and an integer parameter). This generates two different versions of the lambda (one with a string literal parameter, and one with an integer parameter).

Most of the time, this is inconsequential. However, note that if the generic lambda uses static duration variables, those variables are not shared between the generated lambdas.

We can see this in the example above, where each type (string literals and integers) has its own unique count! Although we only wrote the lambda once, two lambdas were generated -- and each has its own version of callCount. To have a shared counter between the two generated lambdas, we’d have to define a global variable or a static local variable outside of the lambda. As you know from previous lessons, both global- and static local variables can cause problems and make it more difficult to understand code. We’ll be able to avoid those variables after talking about lambda captures in the next lesson.

Return type deduction and trailing return types

If return type deduction is used, a lambda’s return type is deduced from the return-statements inside the lambda. If return type inference is used, all return statements in the lambda must return the same type (otherwise the compiler won’t know which one to prefer).

For example:

This produces a compile error because the return type of the first return statement (int) doesn’t match the return type of the second return statement (double).

In the case where we’re returning different types, we have two options:
1) Do explicit casts to make all the return types match, or
2) explicitly specify a return type for the lambda, and let the compiler do implicit conversions.

The second case is usually the better choice:

That way, if you ever decide to change the return type, you (usually) only need to change the lambda’s return type, and not touch the lambda body.

Standard library function objects

For common operations (e.g. addition, negation, or comparison) you don’t need to write your own lambdas, because the standard library comes with many basic callable objects that can be used instead. These are defined in the <functional> header.

In the following example:

Output

99 90 80 40 13 5

Instead of converting our greater function to a lambda (which would obscure its meaning a bit), we can instead use std::greater:

Output

99 90 80 40 13 5

Conclusion

Lambdas and the algorithm library may seem unnecessarily complicated when compared to a solution that uses a loop. However, this combination can allow some very powerful operations in just a few lines of code, and can be more readable than writing your own loops. On top of that, the algorithm library features powerful and easy-to-use parallelism, which you won’t get with loops. Upgrading source code that uses library functions is easier than upgrading code that uses loops.

Lambdas are great, but they don’t replace regular functions for all cases. Prefer regular functions for non-trivial and reusable cases.

Quiz time

Question #1


Create a struct Student that stores the name and points of a student. Create an array of students and use std::max_element to find the student with the most points, then print that student’s name. std::max_element takes the begin and end of a list, and a function that takes 2 parameters and returns true if the first argument is less than the second.

Given the following array

your program should print

Dan is the best student

Show Hint

Show Solution

Question #2

Use std::sort and a lambda in the following code to sort the seasons by ascending average temperature.

The program should print

Winter
Spring
Fall
Summer

Show Solution


10.16 -- Lambda captures
Index
10.14 -- Ellipsis (and why to avoid them)

129 comments to 10.15 — Introduction to lambdas (anonymous functions)

  • i am getting an error
    main.cpp:23:8: error: ‘void best’ has incomplete type.

  • Szymon :)

    Why does this work (lambda should be returning a double, but returns a bool; why is there no error)?

    • Alex

      In Visual Studio, here's how find_if is implemented:

      The thing to key on here is this line:

      _Pred is your lambda, so the (double) return value of your lambda is being implicitly converted into a bool when the if statement is evaluated.

      • Szymon :)

        Oh, thank you very much! I've got some quick questions:
        1. How do I make an avatar on this site?
        2. How do I delete or edit comments?

        • Alex

          1. See https://www.learncpp.com/cpp-tutorial/introduction-to-these-tutorials/
          2. You should be able to delete or edit your comments within 60 minutes of posting them.

  • Haldhar Patel

    Hi
    We can use a lambda variable instead of just putting the lamda definition inside the function, which will look much cleaner according to the lesson best practice:

  • batman47steam

    hi,i have some question here,you said that
    >Unfortunately, we can’t always use auto. In cases where the actual lambda is unknown (e.g. because we’re passing a lambda to a function as a parameter and the caller determines what lambda will be passed in)

    why can't we use auto here,i tried to use auto instead of std::functon in void repeat(int, const std::function)
    and it works fine, do you mean that if we have a different type of lambda, like which takes two parameters [](int int) {} and then when we
    call fn(i) in the repeat, it will cause some error? so we have to use std::function to specify the parameter and return type?
    hope for the answer, and thank you for creating this greet website

    • nascardriver

      Thanks for pointing this out!

      `auto` parameters were added in C++20, this lesson was written before that. I've added a sentence about why `auto` parameter can be problematic after the example.

  • gerry laisina

    Hi Alex and Nascardriver.
    I wanna ask something related to this snippet of code below:

    from what i've learned in "function pointer", std::function is seemingly like some kind of type, usually utilized to declare and store some pointer of function,
    and according to your explanation in the "Rule" section in the next chapter, you say that we actually never pass lambda by reference.

    So why are we using "&" operator alongside "std::function" to pass lambda to a function here?
    Thanks before.

    • nascardriver

      `std::function` is potentially a large type (it stores the entire callable object, which can have arbitrary size). Large objects should be passed by reference.

      • gerry laisina

        i just returned from chapter 10.16.

        from your explanation in "Unintended copies of mutable lambdas" section in the chapter 10.16, you said that "When std::function is created with a lambda, the std::function internally makes a copy of the lambda object. Thus, our call to fn() is actually being executed on the copy of our lambda, not the actual lambda."

        So if we're supposed to pass large object such as lambda by reference, although std::function is gonna make a copy of the object, what's the actual purpose of the '&' operator here? what's gonna happen if i just discard the '&' operator here?

        Sorry sir, i think i just got a bit stuck in here.
        Thanks again!

        • nascardriver

          • gerry laisina

            So, do you mean, if we pass lambda by value, there's gonna be one 'extra' (but useless) copy of lambda inside std::function (2 lambdas in total)?

            I hope i get this right this time.
            Thanks again!

            • nascardriver

              Yes. If you store a lambda in a `std::function`, you're copying it.
              If you pass any variable by value, you're copying (or moving) it.

  • Sahil

    Hi, I think I've understood the syntax of lambdas pretty well (which I think was the purpose of the exercise) but now I'm a bit confused about those return statements that we used in the lambdas. I ended up using the wrong </> sign in both cases only to realize the  mistake after the first run. Would you please explain in short when to use which sign.

    Thanks

    • nascardriver

      That's a greater than/less than sign.
      a < b is true if a is less than b
      a > b is true if a is greater than b

      • Patrick

        So when a < b evaluates to true, b becomes the max element? I was just a little confused because for std::sort, if the comparison function returns true, 'a' (the first param) is ordered before b. So I thought that for std::max_element, if the comp. function returned true, then 'a' would become the greatest element.

        But for a < b, if this evaluates to true, it wouldn't make sense for 'a' to be the greatest element...

        Edit:
        Ok, I think I understand it better now after reading this:
        The value returned indicates whether the element passed as the first argument is considered less than the second.

        From https://www.cplusplus.com/reference/algorithm/max_element/#:~:text=std::max_element&text=Returns an iterator pointing to,not compare less than it.

  • Rt

    In Generic lambdas and static variables you say
    > For now, this means defining the variable even outside of the function the lambda is defined in. In the above example, this means adding a global variable.

    I just moved the line

    outside the lambda and it worked:

    The return is this:

    0: hello
    1: world
    2: 1
    3: 2
    4: ding dong

    So we are able to do this without a global variable though?

    • nascardriver

      Hi, that was an oversight on my part. Thank you for experimenting! I've updated the lesson.

    • Sahil

      That is not what I was looking for, I wanted to know how the true/false from that return help the std::max_element or std::sort, but I looked at a previous lesson and got it, now I kind of feel dumb for even asking the question in the first place...

      Thanks for the site and helping thought :)

  • J34NP3T3R

    in Question #1

    what type does max_element return ? it seems like a pointer to a pointer. originally i made it without the * in std::max_element but later found i need to put the *.
    i was trying to copy the answer which said i must use const auto

    must be a pointer to a pointer since we are using ->
    why cant i use

    instead of

    • J34NP3T3R

      if i use auto as the type to catch the return type of max_element , what is actually the type thrown back by max_element ?

      • nascardriver

        `std::max_element` returns the same type that the parameters have
        https://en.cppreference.com/w/cpp/algorithm/max_element

        In this specific case, `std::array<Student, 8>::iterator`

  • Ok, this lambda syntax initially tickled  my brain, but I think I got it now!

    Main benefit of Lambda = no need to write a comparator function for <algorithm> functions like std::sort, std::max_element, etc...

    For anyone confused, please check out my notes below. I think this is a good way to think about this. :)

  • Copy/Pasting the solution for Question 1 produces this error message in Virtual Studio 2019:

    Severity    Code    Description    Project    File    Line    Suppression State
    Error    MSB3491    Could not write lines to file "Debug\10.15 — .f1626984.tlog\10.15 — Introduction to lambdas (anonymous functions) Question 1.lastbuildstate". Path: Debug\10.15 — .f1626984.tlog\10.15 — Introduction to lambdas (anonymous functions) Question 1.lastbuildstate exceeds the OS max path limit. The fully qualified file name must be less than 260 characters.    10.15 — Introduction to lambdas (anonymous functions) Question 1    C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Microsoft\VC\v160\Microsoft.CppBuild.targets    354

  • Uyph

    Hi, is there any reason we're using std::string_view rather than std::string in Quiz #2?

    • nascardriver

      We know that there are only 4 seasons, there will never be more or less, and we know their names at compile time.

      If you can't provide the season names as compile-time strings, you need to use `std::string` to make the `Season` own the string.

  • Pablo

    Hi, can you tell me what's the error in my code:

    I get this error message:

    ||=== Build: Debug in LearnCPP715-1 (compiler: GNU GCC Compiler) ===|
    C:\CBProjects\LearnCPP715-1\main.cpp||In function 'int main()':|
    C:\CBProjects\LearnCPP715-1\main.cpp|28|error: could not convert 'std::max_element<Student*, main()::<lambda(Student, Student)> >(std::begin<std::array<Student, 8> >(students), std::end<std::array<Student, 8> >(students), (<lambda closure object>main()::<lambda(Student, Student)>{}, main()::<lambda(Student, Student)>()))' from 'Student*' to 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'}|
    C:\CBProjects\LearnCPP715-1\main.cpp|34|error: missing initializer for member 'Student::points' [-Werror=missing-field-initializers]|
    ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

  • sergey

    How is this:

    better than this:

    ?

  • yeokaiwei

    2. I do not fully understand lambdas. I just understand it as shorthand. I have an idea of the syntax but what am I doing is following the syntax for Quiz 2.

    Quiz 2 is easier to do because the answer is similar to Quiz 1.

    I'm still stuck with when references should be used.

    3. Here are my assumptions.
    a. I assume we use "auto" because users won't have to know what type was defined in the array-structs. The type in the struct can be hidden E.g. ??? points. Auto just matches the ???.
    b. We use "&" (references) because arrays decay to pointers
    c. We use "const" to ensure that we don't accidentally change the value in the array-struct. It isn't actually necessary to have "const" to solve Quiz 2.
    d. Lambdas are just shorthand so you don't have to write a boolean function with input parameters, return function.

    • nascardriver

      3.
      a. The developer knows the type is `Season`, because that's the type of the elements in `seasons`. But because the developer already knows what type the elements have, there's no need to repeat the type. `auto` makes the code less repetitive.

      b. `std::array` doesn't decay. `ref1` and `ref2` are not arrays. We use references because copying non-fundamental types is slow. Without using references, `std::sort` would copy 2 elements every time it calls the comparison function.

      c. In general, we use `const` to ensure we don't accidentally change the value of the object. But it is required for `std::sort` and many other functions. Non-const references can only bind to lvalues, ie. not to temporaries.

      `std::sort` requires the comparison function to be usable with any value category, including temporaries. I don't see why `std::sort` would do that, but it wants to be able to do so, so we have to comply. You're compiler probably accepts the code with non-const references, that doesn't mean it's correct, the code could fail to compile with a different compiler.
      d. Yes

  • yeokaiwei

    Lambdas are pretty hard to wrap one's head around. I can't do lambdas without hints or solution. Too many errors occur.

    • nascardriver

      None of your ERROR comments are related to lambdas, but iterators.

      1. `std::max_element` returns an iterator of `arr`. The element an iterator is pointing to can be accessed with `best->name` or `*best`. `arr`'s elements are `Student`, so `*best` returns a `Student` reference.

      2. `arr` is a `std::array`, you need to select an element of the array first.

      3. `std::max_element` passes the elements of the container to the comparison function. The elements of the container are `Student`s, not `int`s.

      4. `best` is an iterator.

      • yeokaiwei

        I think I'm going to be a little confused with lambdas.

        This is what I know.

        1. Lambdas are functors.
        2. Lambdas are not just function pointers. Function pointers are a subset of functors.
        3. Lambdas are NOT iterators?

        • nascardriver

          I'm not familiar with the term "functor". I'll treat it as "anything that's callable", if I'm wrong please correct me.

          1. Yes
          2. Lambdas are not function pointers. Please ask again after lesson 9.9, that's when I'll be able to tell you more. Without operator overloading it's hard to explain how lambdas work. Function pointers can point at some functors. `std::function` can "point at" all functors.
          3. Lambdas have nothing to do with iterators. An iterator is something that knows how to walk through a container. A lambda is a function-like thing. Iterators and lambdas often occur together when used for standard algorithms.

          • yeokaiwei

            Ok, got it.

            1. Lambdas are functors, whatever they are.
            2. Lambdas are NOT function pointers
            3. Lambdas are NOT iterators

            You could add the above to a quiz on lambdas.

  • Rishi

    Paragraph 1:Lamdas to the rescue:
    It was written "naming pollution". Shouldn't it be naming collision?

  • Mauri FC

    I'm using Visual Studio 2017 and this doesn't work for me:

    But this does:

  • srt1104

    Under "Generic lambdas and static variables" section, you have stated: "To have a shared counter between the two generated lambdas, we’d have to define a variable outside of the lambda. For now, this means defining the variable even outside of the function the lambda is defined in." Why so? Wouldn't it suffice to define the shared counter at the starting of main() since the lambda is being used only within main()?

    Edit: Just read the next lesson. I get it now.

  • Ryan

    Hi. In terms of performance, should we use functions or lamdas why?

    • nascardriver

      You're comparing cars to trains. If you live next to a train station, take the train. If you live in a desert, take the car.
      Don't use what you think will be generally faster. Use what fits the situation best.
      Either one can run as fast as the other. If you're developing a performance-critical application, run benchmarks.

  • Lordi

    my solution for the question #2
    just why did you use const?

    • nascardriver

      The more `const` the better. It prevents you from accidentally modifying something, and also makes your code easier to understand because the reader doesn't have to worry about variables changing their values.

  • Tony

    Hi @nascardriver!

    I have 3 questions for quiz 1.

    1) What does the "->" do here? How does it work? Sorry, but I seem to have missed this.

    2) I tried using a for loop prior to watching the hit (to print the correct name) but I failed. So is there another way to replace  that -> in this case?

    3) dumb question. What's the purpose of & in lambda parameters?

    Thanks!

    EDIT:
    1>Member selection. But, is "best" a pointer?

    2>nevermind I guess

    3>Oh, "auto" is "Student"! I now see why you used a reference there.

    • Tony

      I can't understand the "->" member selection here.

      So we are accessing struct "Student" through a variable "best" that isn't of type Student? I can't get it...

      EDIT:
      I tried replacing "auto best" with "Student *best" and it seems to work just the same. Is this the reason as to why we can access the Student's member through "best"? Because in reality that auto is of type Student? Sorry for bothering.

    • nascardriver

      Hii Tony

      1) `best` is an iterator. Iterators can be accessed the same way as pointers. See the lesson about iterators

      2) I don't understand. Can you show the code that you tried and tell me what you expected it to do?

      3) That's a reference, like in normal functions. `a` and `b` are `const Student&`. Without the reference, we'd copy the students many times, which is unnecessary and expensive. See the lesson about passing arguments by reference.

      Now I see you already answered your questions, nevermind I guess

      `best` is _not_ a pointer. It might be (convertible to) a pointer with your compiler, but that's not always the case. `best` is a `std::array<Student, 8>::iterator` (That's a type alias and might refer to `Student*` but could but an entirely different type). Most often, `auto` is used for iterators, because their type doesn't matter. It only matter how we can use them, and that's always the same.

  • Lucky Abby

    my solution:

  • Putin

    thanks so much @nascardriver, i understand it better now.

  • Putin

    Hi,

    I'm a bit confused with the output result for "Generic lambdas and static variables"
    i understand that the first and second call to function print() output  "0: hello and
    1: world" however, the third and fourth call also take same process which prints "0: 1 and 1: 2". What got me confused is the fifth call to function print(), i expect the output to be "0: ding dong" but it outputs "2: ding dong" instead. Could you please, make this more clearer why it was like that? Thank you.

    • nascardriver

      The compiler generated 2 versions of `print`. One with a `const char*` parameter, and one with an `int` parameter. Each of those versions has a `callCount`. `callCount` never gets reset.
      The first 2 calls call the `const char*`, increasing its `callCount` to 2.
      Then the `int` version gets called and its `callCount` is also incremented to 2.
      Now the `const char*` version (Its `callCount` is still 2) is called again and its `callCount` is incremented to 3.

  • Tony

    "The syntax for lambdas is one of the weirder things in C++, and takes a bit of getting used to. Lambdas take the form:"

    Perhaps you meant "weirdest" there! :D

Leave a Comment

Put all code inside code tags: [code]your code here[/code]