Lambda functions (since C++11)
From cppreference.com
This section is incomplete |
Declares an unnamed function object
Contents |
[edit] Syntax
[ capture ] ( params ) -> ret { body } | |||||||||
[ capture ] ( params ) { body } | |||||||||
[ capture ] { body } | |||||||||
This section is incomplete |
[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:
|
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; c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; } ), c.end()); 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
auto specifier | specifies a type defined by an expression (C++11) |
(C++11) |
wraps callable object of any type with specified function call signature (class template) |