Lambda expressions in C ++ 11

Source: Internet
Author: User

Lambda Expressions in C ++
Lambda expressions in C ++


In Visual C ++, a lambda expression-referred to as a lambda-is like an anonymous function that maintains state and can access the variables that are available to the enclosing scope. this article defines what lambdas are, compares them to other programming techniques, describes their advantages, and provides a basic example.

In VC ++, a lambda expression refers to a lambda (Greek letter). Like an anonymous function, it maintains the state and can access variables (in the scope (enclosing scope) ). This article defines what Lambda expressions are, compares them with other programming technologies, describes their advantages, and provides basic examples.
About Lambdas
Extends programming versions support the concept of an anonymous function, which is a function that has a body, but doesn't have a name. A lambda is a programming technique that's related to anonymous functions. A lambda implicitly defines a function object class and constructs a function object of that class type. for more information about function objects, see Function Objects.

Many programming languages support the concept of anonymous functions. Anonymous functions are functions without names. Lambda is a new technology that relies on anonymous functions. (Implicit) Lambda expressions define a function class and use it (function class) as a function object (class instantiation object, see Baidu encyclopedia ). For more information, see Function Objects in the MSDN library.
Function Objects vs. Lambdas
When you write code, you probably use function pointers and function objects to solve problems and perform calculations, especially when you use STL algorithms. function pointers and function objects have advantages and disadvantages-for example, function pointers have minimal syntactic overhead but do not retain state within a scope, and function objects can maintain state but require the syntactic overhead of a class definition.

A lambda combines the benefits of function pointers and function objects and avoids their disadvantages. like a function objects, a lambda is flexible and can maintain state, but unlike a function object, its compact syntax doesn't require a class definition. by using lambdas, you can write code that's less cumbersome and less prone to errors than the code for an equivalent function object.

The following examples compare the use of a lambda to the use of a function object. the first example uses a lambda 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.

When writing code, you may use function pointers or function objects to solve problems or perform computations, especially when you use STL algorithms. Function pointers and function objects (or can they be understood as imitation functions ?) Advantages and disadvantages-for example, function pointers have the minimum syntax overhead (?) But it cannot be in the scope (?), While function objects can maintain the state, they need to define a class (relatively large syntax overhead)
Lambda expressions combine their advantages and disadvantages. Like function objects, Lambda expressions are flexible (this is difficult to understand !!) It can be kept in a State and does not require function objects. Its complete syntax does not require class definition. Using lambda expressions can make your code less complex and reduce errors.
The following examples compare lambda expressions and function objects. The first example uses the lambda expression to output the parity of elements in the Vector container in the console. The second uses the function object to implement the same task.
Example 1: Using a Lambda
This example uses a lambda that's embedded in the for_each function call to print to the console whether each element in a vector object is even or odd.

This example uses a lambda expression embedded in the for_each function to output the parity of elements in the vector in the console.
 

// Even_lambda.cpp
// Compile with: cl/ehs/ nologo/W4/MTd
# 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
// Using the for_each function and a lambda.
Int evenCount = 0;
For_each (v. begin (), v. end (), [& evenCount] (int n ){
Cout <n;
 
If (n % 2 = 0 ){
Cout <"is even" <endl;
++ 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;
}

// Even_lambda.cpp
// Compile with: cl/ehs/ nologo/W4/MTd
# 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
// Using the for_each function and a lambda.
Int evenCount = 0;
For_each (v. begin (), v. end (), [& evenCount] (int n ){
Cout <n;

If (n % 2 = 0 ){
Cout <"is even" <endl;
++ 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 the example, the third argument to the for_each function is a lambda. 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.

In this example, the third for_each parameter is a lambda expression. The [& evenCount] section clearly describes the clause expression, and (int n) explicitly describes a form parameter (parameter ?) List, the rest is the subject of the expression.
Example 2: Using a Function Object
Sometimes a lambda wocould be too unwieldy to extend much further than the previous example. the next example uses a function object instead of a lambda, together with the for_each function, to produce the same results as Example 1. both examples store the count of even numbers in a vector object. to maintain the state of the operation, the FunctorClass stores the m_evenCount variable by reference as a member variable. to perform the operation, FunctorClass implements the function-call operator, operator (). the Visual C ++ compiler generates code that is comparable in size and performance to the lambda code in Example 1. for a basic problem like the one in this article, the simpler lambda design is probably better than the function-object design. however, if you think that the functionality might require significant expansion in the future, then use a function object design so that code maintenance will be easier.

For more information about the operator (), see Function Call (C ++). For more information about the for_eachfunction, see for_each.

Sometimes lambda expressions are too complicated (extended ). The next example uses the function object and for_each. All are even numbers in the vector element. To maintain the operation state, the FunctorClass class saves the m_evenCount variable as a reference to a member variable. To implement the function, FunctorClass overload (implement ?) The function-call operator, operator (). The VC ++ compiler produces lambda Expression Code equivalent to the equivalent size and performance (Example 1 ). In this basic problem, the simple lambda expression design may be better than the function object. However, if you think functionality (functional ?) A clear extension may be required, so it is easier to use function objects to write code.
For operator () and for_each, refer to Function Call (C ++) and for_each, which are available in the MSDN library.
[Cpp]
// Even_functor.cpp
// Compile with:/ESCs
# Include <algorithm>
# Include <iostream>
# Include <vector>
Using namespace std;
 
Class FunctorClass
{
Public:
// The required constructor for this example.
Explicit FunctorClass (int & evenCount)
: M_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) const
{
Cout <n;
 
If (n % 2 = 0 ){
Cout <"is even" <endl;
++ M_evenCount;
} Else {
Cout <"is odd" <endl;
}
}
 
Private:
// Default assignment operator to silence warning C4512.
FunctorClass & operator = (const FunctorClass &);
 
Int & m_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
// Using the for_each function and a function object.
Int evenCount = 0;
For_each (v. begin (), v. end (), FunctorClass (evenCount ));
 
// Print the count of even numbers to the console.
Cout <"There are" <evenCount
<"Even numbers in the vector." <endl;
}

// Even_functor.cpp
// Compile with:/ESCs
# Include <algorithm>
# Include <iostream>
# Include <vector>
Using namespace std;

Class FunctorClass
{
Public:
// The required constructor for this example.
Explicit FunctorClass (int & evenCount)
: M_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) const
{
Cout <n;

If (n % 2 = 0 ){
Cout <"is even" <endl;
++ M_evenCount;
} Else {
Cout <"is odd" <endl;
}
}

Private:
// Default assignment operator to silence warning C4512.
FunctorClass & operator = (const FunctorClass &);

Int & m_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
// Using the for_each function and a function object.
Int evenCount = 0;
For_each (v. begin (), v. end (), FunctorClass (evenCount ));

// Print the count of even numbers to the console.
Cout <"There are" <evenCount
<"Even numbers in the vector." <endl;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.