Namespaces
Variants
Views
Actions

Lambda functions (since C++11)

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

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.
  • [this] captures the this pointer
  • [&] 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;
    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) [edit]
(C++11)
wraps callable object of any type with specified function call signature
(class template) [edit]