What are Lambda Expressions? - C++ STL

C++ examples for STL:Lambda

Introduction

Lambda Expressions enable the creation of inline anonymous functions.

The expression is stored in a variable and called like a function.

auto a = [](){ std::cout << "this is a test!" << std::endl; }; 
a(); 

The lambda expression can have one or more arguments, which are specified within the parenthesis marks after the [ ] square brackets.

This example has two arguments:

auto multiply = [](int x, int y){ std::cout << "Total: " << x * y << std::endl; }; 
multiply(7, 17); 

When a lambda expression has no arguments, the parentheses can be left out of the expression.

The first example didn't have any, so here's another version of that expression:

auto a = []{ std::cout << "test" << std::endl; }; 

The expression can return a value by specifying its return type (or auto) after a -> operator.

Here's a rewrite of the previous example that returns the sum of multiplying x and y.

auto multiply = [](int x, int y) -> int { return x * y; }; 
int sum = multiply(7, 17); 
std::cout << "Total: " << sum << std::endl; 

You can use local variable with the [ ] square brackets, which are called the capture block.

To make one or more variables from the enclosing scope available in the lambda expression, list them inside the [ and ] brackets separated by commas.

This code puts the capture block to use:

int x = 7; 
auto multiply = [x](int y) -> int { return x * y; }; 
int sum = multiply(17); 
std::cout << "Total: " << sum << std::endl;

Related Tutorials