Lambda Expressions in C++
This topic provides an overview of lambda expressions in Visual C++. It defines what lambda expressions are, compares them to other programming techniques, describes their advantages, and provides a simple example.
About Lambda Expressions
Many programming languages support the concept of an anonymous function. A lambda expression is a programming technique that is related to anonymous functions. An anonymous function is a function that has a body, but does not have a name. A lambda expression implicitly defines a function object class and constructs a function object of that class type. You can think of a lambda expression as an anonymous function that maintains state and that can access the variables that are available to the enclosing scope.
Примечание
For more information about function objects, see Function Objects.
Function Objects vs. Lambda Expressions
When writing code, you probably use function pointers and function objects to solve problems and perform calculations. Both function pointers and function objects have advantages and disadvantages: function pointers involve minimal syntactic overhead, but they do not retain state within a scope; function objects can maintain state, but they require the syntactic overhead of a class definition.
Lambda expressions are a programming technique that combines the benefits of function pointers and function objects and that avoids their disadvantages. Lambda expressions are flexible and can maintain state, just like function objects, and their compact syntax removes the need for a class definition, which function objects require. Lambda expressions enable you to write code that is less cumbersome and less prone to errors than an equivalent function object.
The following examples compare the use of a lambda expression to the use of a function object. The first example uses a lambda expression to print to the console whether each element in a vector object is even or odd. The second example uses a function object to accomplish the same task.
Example 1: Using a Lambda Expression
Description
The following example uses a lambda expression and the for_each function to print to the console whether each element in a vector object is even or odd.
Code
// even_lambda.cpp
// compile with: /EHsc
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a lambda expression.
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount] (int n) {
cout << n;
if (n % 2 == 0)
{
cout << " is even " << endl;
// Increment the counter.
evenCount++;
}
else
{
cout << " is odd " << endl;
}
});
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
Output
0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
There are 5 even numbers in the vector.
Comments
In this example, the third argument to the for_each function is a lambda expression. The [&evenCount] part specifies the capture clause of the expression, (int n) specifies the parameter list, and remaining part specifies the body of the expression.
Example 2: Using a Function Object
Description
The following example uses a function object and the for_each function to produce the same results as Example 1. The function object also stores the count of even numbers in the vector object. To maintain the state of the operation, the Functor class stores the_evenCount variable by reference as a member variable. To perform the operation, the Functor class implements the function-call operator, operator().The Visual C++ compiler generates code that is comparable both in size and performance to Example 1, which uses a lambda expression.
Примечание
: For more information about the function call operator, see Function Call (C++). For more information about the for_each function, see for_each.
Code
// even_functor.cpp
// compile with: /EHsc
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Functor
{
public:
// The constructor.
explicit Functor(int& evenCount)
: _evenCount(evenCount)
{
}
// The function-call operator prints whether the number is
// even or odd. If the number is even, this method updates
// the counter.
void operator()(int n)
{
cout << n;
if (n % 2 == 0)
{
cout << " is even " << endl;
// Increment the counter.
_evenCount++;
}
else
{
cout << " is odd " << endl;
}
}
private:
int& _evenCount; // the number of even variables in the vector
};
int main()
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i)
{
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a function object.
int evenCount = 0;
for_each(v.begin(), v.end(), Functor(evenCount));
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
}
Summary
Lambda expressions are a powerful and expressive programming technique. To learn about the parts and properties of a lambda expression, see Lambda Expression Syntax. To learn how to use lambda expressions in your programs, see Examples of Lambda Expressions.