Lambda functions (since C++11)

From Cppreference

Jump to: navigation, search

Declares an unnamed function object

Contents

[edit] Syntax

[ capture ] ( params ) -> ret { body }
[ capture ] ( params ) { body }
[ capture ] { body }

[edit] Explanation

capture - specifies which symbols visible in the scope where the function is declared will be visible inside the function body.

A list of symbols can be passed as follows:

  • [a,&b] where a is captured by value and b is captured by reference.
  • [&] captures all symbols by reference
  • [=] captures all by value
  • [] captures nothing
params - The list of parameters, as in named functions
ret - Return type. If not present it's implied by the function return statements ( or void if it doesn't return any value)
body - Function body

[edit] Example

This example shows how to pass a lambda to a generic algorithm and that objects resulting from a lambda declaration, can be stored in std::function objects.

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
 
int main()
{
    std::vector<int> c { 1,2,3,4,5,6,7 };
    int x = 5;
    std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; } );
 
    std::cout << "c: ";
    for (auto i: c) {
        std::cout << i << ' ';
    }
    std::cout << '\n';
 
    std::function<int (int)> func = [](int i) { return i+4; };
    std::cout << "func: " << func(6) << '\n'; 
}

Output:

c: 5 6 7
func: 10

[edit] See also

(C++11)
wraps callable object of any type with specified function call signature
(class template)
(keyword)