C ++ 0x Study Notes lambda

Source: Internet
Author: User

By feng

With lambda support, it is easier to write some functional code, such

123 std::vector<int> vec; std::for_each( vec.begin(), vec.end(),                [](int i){ std::cout <<i << ""; } );

For example

12 std::sort( vec.begin(), vec.end(), [](int i, int j)            { return std::abs(i) < std::abs(j); } );

The

1 [](int i, int j){return std::abs(i) < std::abs(j);}

Is a lambda object. The type returned by this anonymous object is

1 decltype(std::abs(j)<std::abs(j))

Note that the return type can be ignored only when a return expression exists in a lambda object; otherwise, it is void. Therefore, this lambda object is written down like this:

12 [](int i, int j) -> bool{ return std::abs(i) < std::abs(j); }

[] Is called the lambda-introducer. It can be empty or have several variable names:

[] // No parameters are defined
[X, & y] // x is passed in as a value, and y is passed in as a reference
[&] // All external parameters are passed in as references
[=] // All external parameters are passed in as values
[&, X] // x is passed in as a value, and others are passed in as references
[=, & Z] // z is passed in as a reference, and others are passed in as values

Below is an example of using external parameters

1234 std::vector<double> arr; double sum = 0; std::for_each( arr.begin(), arr.end(),                [&sum](double d){ sum += std::exp(d); } );

Sum is passed in as a reference, which is equivalent to Calculation

And save the result to sum.

Of course, the reference of all external parameters can also be directly captured in the preceding section for simplification, which is useful in many parameters.

 

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.