C++ Lambdas

  1. What are Lambdas

    Lambda is a convenient way of defining an anonymous function right at the location where it's invoked or passed as an argument to a function.

  2. How to write Lambdas

    You write capture closure in [] then in () you write arguments for your function and then you write function body in {}

    auto lambda = [](){ std::cout << "This is a lambda function" << std::endl; };

    and then you can use it just as a normal function

    auto lambda = [](){ std::cout << "This is a lambda function" << std::endl; };
    lambda();

    In capture closure you can specify the mode it captures everything from outside. = mode passes everything by value. & mode passes everything by reference. Nothing set in [] won't capture anything. variable_name passes specified variable only.
    For example you have variable a set to 5 then you have lambda defined in variable and then you invoke that lambda in a for loop. The variable a will be captured by lambda if you will set mode to = or &.

    int a = 5;
    auto lambda = [=](int value) {std::cout << value << " " << a << std::endl;}; // a will be captured by value
     
    for(int i = 0; i < 5; i++){ 
        // we have access to value of 'a' inside this scope
        lambda(i);
    }