# 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.

Note

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.

Note

: 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.

## See Also

#### Reference

Function Call (C++)

for_each

Function Objects

#### Other Resources

C++ Language Reference
{"ft_lang_label":"__label__en","ft_lang_prob":0.7881923,"math_prob":0.94581616,"size":5402,"snap":"2019-13-2019-22","text_gpt3_token_len":1172,"char_repetition_ratio":0.17876992,"word_repetition_ratio":0.27524972,"special_character_ratio":0.23861533,"punctuation_ratio":0.12029289,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.993831,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-05-19T17:16:39Z\",\"WARC-Record-ID\":\"<urn:uuid:7d7c686f-d3c4-4718-984d-30e0c93fcbbd>\",\"Content-Length\":\"28819\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:9affb967-3d12-4dbd-887c-00c34eef141d>\",\"WARC-Concurrent-To\":\"<urn:uuid:12fc0bad-0c5f-46bd-a3e7-906d3f2bfdfd>\",\"WARC-IP-Address\":\"104.91.71.145\",\"WARC-Target-URI\":\"https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/dd293608(v=vs.100)\",\"WARC-Payload-Digest\":\"sha1:WNQGYPIBYBFQGVLE6D6JHGJ3PLQETMUE\",\"WARC-Block-Digest\":\"sha1:DFWKR2CKMM64I7L7TDXDJSSDYUJO7N53\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-22/CC-MAIN-2019-22_segments_1558232255071.27_warc_CC-MAIN-20190519161546-20190519183546-00039.warc.gz\"}"}