Code Concise Way: C + + 11 auto+ for_each + LAMDA expression

Source: Internet
Author: User

Absrtact: In many cases, we need to perform similar processing for each element in the vector (each element +1, or other). In general, we will use a for loop and then process each element. In fact, C + + 11 provides LAMDA expressions, combined with for_each, to write more concise and efficient code.


1.for_each. Introduction

For_each is a template in C + +, which you can refer to here: http://www.cplusplus.com/reference/algorithm/for_each/


2.lamda-expression

Lamda expressions, also in Python, are simply anonymous functions. For examples and detailed usage of LAMDA expressions, we can refer to this: Http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B

C++11 provides support for anonymous functions, called lambda functions (also called lambda expressions). The lambda expression is specific in the following form:

[Capture] (parameters)->return-type{body}
capture: External variables to be used, parameters: function parameters; body: function Body
If there are no parameters, empty parentheses () can be omitted. The return value can also be omitted if the function body consists of only one return statement or the return type is void. Shape:

[Capture] (parameters) {body}

Here are some examples of lambda functions:

[] (int x, int y) {return x + y;}//implicit return type
[] (int& x) {++x;} The return type of the lambda function with no return statement is ' void '
[A] (int& x) {x+=a;} The return type of the lambda function without the return statement is ' void '; Note that a is a variable passed in from outside the body of the lambda function .
[] () {++global_x;} No parameters, access only one global variable
[]{++global_x;} Same as Previous, omitted ()
You can display the specified return type as follows:
[] (int x, int y), int {int z = x + y; return z;}
in this example, a temporary variable z is created to store the middle value. Like normal functions, this intermediate value is not saved to the next call. Nothing returns a lambda function that omits the return type and does not need to use the-void form.
A lambda function can refer to a variable declared outside of it. The collection of these variables is called a closure. Closures are defined within the brackets [] in the lambda expression Declaration. This mechanism allows these variables to be captured by value or by reference. The following examples are:

[]        //undefined variable. It is an error to attempt to use any external variables within a lambda. [X, &y]   X is captured by value and Y is captured by reference. [&]       Any external variables that are used implicitly by reference capture [=]       //are implicitly captured by value [&, X]//x are explicitly captured by    value. Other variables are captured by reference [=, &z]   //z by reference. Other variables are captured by value
The next two examples demonstrate the use of lambda expressions.
std::vector<int> some_list;int total = 0;for (int i=0;i<5;++i) some_list.push_back (i); Std::for_each (Begin ( Some_list), End (Some_list), [&total] (int x) {Total    + = x;});

This example calculates the sum of all the elements in the list. The variable total is saved as part of the lambda function closure. Because it is a reference to the stack variable (local variable) total, you can change its value.
Std::vector<int> some_list;  int total = 0;  int value = 5;  Std::for_each (Begin (Some_list), End (Some_list), [&, value, this] (int. x)   {Total    + = x * Value * This->som E_func ();  });

in this example, total is saved as a reference, and value copies a copy of the value. The capture of this is special and can only be captured by value. This can only be captured if the function that contains it is not a static member function. For protect and priviate members, This lambda function has the same access control as the member function that created it. If this is captured, either explicitly or implicitly, the scope of its class is visible to the lambda function. The member accessing this does not have to use the this-> syntax and can be accessed directly.
the implementation of different compilers can vary, but the expected result is that any variable captured by reference, the lambda function actually stores should be a stack pointer to the function of these variables in creating the lambda function, rather than a reference to the lambda function's own stack variable. Anyway, Because a large number of lambda functions are small and in local action, they are similar to the candidate inline functions, so those variables that are captured by reference do not require additional storage space.
If a closed containing reference to a local variable is used beyond the scope where it was created, the behavior is undefined!
A lambda function is an implementation-dependent function object type whose name is only known to the compiler. If the user wants to pass a lambda function as a parameter, the type of the parameter must be a template type or be able to create an std: Function-like objects to capture lambda functions. Use the Auto keyword to help store lambda functions,

3.auto

Auto allows the compiler to infer variable types automatically, for example:

Vector<vector<int> > func (int a, int b); auto func (2,2);

4. Example Leetcode above has a problem, resulting in a full array

Class Solution {public                                 :                                              vector<vector<int> > Permuteunique (vector<int> &num) {        vector<vector<int> > result;                 vector<int> empty;        int n=num.size ();                                if (n==0) {               result.push_back (empty);            return result;                               }                                                Vector<int> Last (Num.begin () +1, Num.end ());        Auto Pre=permuteunique (last);        for (int. i=0;i<n;i++) {            for_each (Pre.begin (), Pre.end (), [N, Num, I, &result] (vector<int> line) {                            Line.insert (Line.begin () +i, num[0]);                            Result.push_back (line);                    });         }           return result;                               }                                            ;  



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.