C++11 new features: Lambda functions (anonymous functions)

Source: Internet
Author: User

Disclaimer: This article refers to Alex Allain's article http://www.cprogramming.com/c++11/c++11-lambda-closures.html

Added their own understanding, not a simple translation

C++11 finally knew to add an anonymous function to the language. Anonymous functions can be handy for coding in many cases, as mentioned later in this article. Anonymous functions in many languages, such as C + +, are implemented with lambda expressions. A lambda expression is also known as a lambda function. I call this a lambda function below.

To understand the usefulness of a lambda function, be sure to first understand the automatic type inference in C + +: http://blog.csdn.net/srzhz/article/details/7934483

Basic lambda functions We can define a lambda function like this: [CPP]View Plaincopy
    1. #include <iostream>
    2. Using namespace std;
    3. int main ()
    4. {
    5. Auto Func = [] () {cout << "Hello World";};
    6. Func (); // now call the function
    7. }

Where Func is a lambda function. We use Auto to get the type of Func, which is very important. Once you have defined the lambda function, you can use it as a function. Where [] means that the next step is to define a lambda function, which may also be filled in between the brackets, as described later. The following () is the function body in the middle of the parameter list {} of the lambda function. Normally, as long as all return in the function body is the same type, the compiler will determine the return type of the function itself. You can also specify the return type of the lambda function to be displayed. This needs to use the function return value of the functions, such as this example: [CPP]View Plaincopy
    1. [] () int { return 1;}
So in general the form of a lambda function is: [CPP]View Plaincopy
    1. [Captures] (params), ret {statments;}
The usefulness of a lambda function assumes that you have designed a class for the Address Book. Now you want to provide a function to query the address Book, may be based on the name of the query, may be based on the address query, there may be a combination of the two. If you write a function for all of these situations, you must be on your knees. So you should provide an interface that makes it easy for users to customize their own query methods. You can use lambda functions here to implement this function. [CPP]View Plaincopy
  1. #include <string>
  2. #include <vector>
  3. Class AddressBook
  4. {
  5. Public :
  6. //Using a template allows us to ignore the differences between functors, function pointers
  7. //And Lambda
  8. template<TypeName func>
  9. Std::vector<std::string> findmatchingaddresses (func func)
  10. {
  11. std::vector<std::string> results;
  12. for (Auto ITR = _addresses.begin (), end = _addresses.end (); ITR! = end; ++itr)
  13. {
  14. //Call the function passed to findmatchingaddresses and see if it matches
  15. if (func (*ITR))
  16. {
  17. Results.push_back (*ITR);
  18. }
  19. }
  20. return results;
  21. }
  22. Private:
  23. Std::vector<std::string> _addresses;
  24. };

As you can see from the code above, the parameters provided by the Findmatchingaddressses function are the Func type, which is a generic type. You should pass in a function in the process, and then execute the function for each entry in the Address Book, if the return value is true so that the entry meets the user's filtering requirements, then it should be put into the result. So how does this func-type parameter pass in? [CPP]View Plaincopy
    1. ADDRESSBOOK&NBSP;GLOBAL_ADDRESS_BOOK;&NBSP;&NBSP;
    2.    
    3. vector<string> findaddressesfromorgs  ()   
    4. {   
    5.     return global_address_ Book.findmatchingaddresses (   
    6.         < span class= "comment" >// we ' re declaring a lambda here; the [] signals  the start  
    7.         []   (const string& addr)  { return  Addr.find (  ". org"  )  != string::npos; }   
    8.     );   
    9. }&NBSP;&NBSP;

As you can see, we define a lambda function directly when we call the function. Parameter type is [CPP]View Plaincopy
    1. Const string& Addr
The return value is of type bool. If the user wants to query in a different way, just define a different lambda function. Variable interception in lambda functions in the above example, the lambda function uses the parameters of the function body and the information inside it, and does not use external information. We envision a scenario where we read a name from the keyboard and then use a lambda function to define an anonymous function that looks for someone with the same name in the Address Book. Then this lambda function is bound to be able to use the variables in the external block, so we have to use the variable intercept function (Variable Capture). [CPP]View Plaincopy
    1. // read in the name  from a user, which we want to search  
    2. string name;  
    3. CIN>>&NBSP;NAME;&NBSP;&NBSP;
    4. return global_address_book.findmatchingaddresses (   
    5.     // notice that the lambda  function uses the the variable  ' name '   
    6.      [&]  (const string& addr)  {  Return name.find ( addr )  != string::npos; }   
As you can see from the code above, our lambda function is already able to use the variable name in the outer scope. One of the biggest differences in this lambda function is that the & symbol is added to the middle. This tells the compiler to take a variable intercept. This allows the lambda function body to use external variables. If you do not add any symbols, the compiler will not take a variable intercept. Here are the options for the various variables to intercept:
    • [] do not intercept any variables
    • [&} intercepts all variables in the outer scope and uses them as references in the body of the function
    • [=] intercepts all variables in the outer scope and copies a copy to be used in the body of the function
    • [=, &foo] Intercepts all variables in the outer scope and copies a copy to be used in the function body, but uses a reference to the Foo variable
    • [bar] Intercept bar variable and copy one copy at function weight without intercepting other variables
    • [This] intercepts the this pointer in the current class. This option is added by default if you have already used & or =.
The introduction of lambda functions and STL lambda functions provides great convenience for the use of STL. For example, when you want to facilitate a vector, you have to write this: [CPP]View Plaincopy
    1. vector<int> v;
    2. V.push_back (1);
    3. V.push_back (2);
    4. //...
    5. for (Auto ITR = V.begin (), end = V.end (); ITR! = end; itr++)
    6. {
    7. cout << *itr;
    8. }
Now that you have a lambda function, you can write this. [CPP]View Plaincopy
    1. vector<int> v;
    2. V.push_back (1);
    3. V.push_back (2);
    4. //...
    5. For_each (V.begin (), V.end (), [] (int val)
    6. {
    7. cout << Val;
    8. } );
And after that, the efficiency of execution improved. Because the compiler is likely to use "loop unwind" to speed up the execution process (secondary school in the computer system architecture course).
Http://www.nwcpp.org/images/stories/lambda.pdf this ppt details how to use lambda expressions and STL

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.