[C ++ learning] function objects and lambda expressions

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

The function object method and Lambda expression are introduced in the first section of efficient programming 18, so that "if you need to customize function pointers more flexibly" is completed ".

Assume that the task determines the parity. to encapsulate the data, we use the function object method:

#include 
#include 
#include 
using namespace std;
class Functor
{
public:
   // The constructor.
   explicit Functor(int& evenCount) 
      : _evenCount(evenCount)
   {
   }
   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() 
{
   vector<int> v;
   for (int i = 0; i < 10; ++i) 
   {
      v.push_back(i);
   }
   int evenCount = 0;
   for_each(v.begin(), v.end(), Functor(evenCount));
   cout << "There are " << evenCount 
        << " even numbers in the vector." << endl;
}

We use a class, which is used to determine the parity and count. In the for_each loop, we pass this functor as a function object and call the functor constructor, when a temporary object is created as a member of a vector, the overloaded () operator acts as a function pointer. Obviously, this method adds flexibility, but it is very laborious to write such a long class.

For the same task, we use the lambda expression to write it again:

#include 
#include 
#include 
using namespace std;
int main() 
{
 
   vector<int> v;
   for (int i = 0; i < 10; ++i) 
   {
      v.push_back(i);
   }
   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;
      }
   });
   cout << "There are " << evenCount 
        << " even numbers in the vector." << endl;
}

Here, we use lambda expressions in the for_each Input Function to write something similar to the anonymous function in Java. The entire program appears naturally smooth. [] The field is the external variable capture rule field of the lambda expression, = Indicates access by value, & Indicates access by reference (these two are used to define default capture rules, if you specify a rule for a single variable, use & in front of the variable name to indicate reference, and write the variable name directly by value). If not, you cannot access any external variables. () Indicates the list of variables in the function body, which is no different from general functions.

1. Lambda expression syntax:

This example of the following edge describes the Syntax:

#include 
#include 
#include 
using namespace std;
// The number of elements in the vector.
const int elementCount = 9;
int main() 
{
   vector<int> v(elementCount, 1);
   int x = 1;
   int y = 1;
   generate_n(v.begin() + 2, elementCount - 2, [&, y]() mutable throw() -> int {
      
      // Generate current value.
      int n = x + y;
      // Update previous two values.
      x = y;
      y = n;
      return n;
   });
   // Print the contents of the vector.
   for_each(v.begin(), v.end(), [](int n) { cout << n << " "; });
   cout << endl;
   cout << x << " " << y << endl;
}

We can see that the STL method generate_n uses the lambda expression at the third parameter position:

[&, Y] () mutable throw ()-> int {}

First, as described above, [] indicates the field of the external variable capture rule. If there is no variable name, it defines the default capture rule of the entire expression, which is referenced here; if a variable is specified, the variable is defined separately. Here, Y is defined separately as value-based capture.

The second field is (), which is an input parameter field. It is similar to a function, but it cannot have default parameters, a variable name, or a variable name. This field is optional.

The third field is the mutable field. If it is set to mutable, the copy of the external variable captured by value can be modified in the expression. Otherwise, the read only error may occur. This field is optional.

The fourth field is the throw field, which limits the exceptions that can be thrown. This field is optional.

The fifth field is-> Field, indicating the type of the returned parameter. If there is only one returned statement, this field can also be omitted, which is determined by the compiler, although this is not recommended. If no value is returned, this field is omitted.

Note: The compilation method of G ++ is g ++-4.5 or above, and the -- STD = C ++ 0x mark is added.

Finally, let's write another example:

#include 
#include 
#include 
int main()
{
   using namespace std;
   // Create a list of integers with a few initial elements.
   list<int> numbers;
   numbers.push_back(13);
   numbers.push_back(17);
   numbers.push_back(42);
   numbers.push_back(46);
   numbers.push_back(99);
   // Use the find_if function and a lambda expression to find the 
   // first even number in the list.
   const list<int>::const_iterator result =
      find_if(numbers.begin(), numbers.end(),
         [](int n) { return (n % 2) == 0; });
   // Print the result.
   if (result != numbers.end())
   {
       cout << "The first even number in the list is " 
            << (*result) 
            << "." 
            << endl;
   }
   else
   {
       cout << "The list contains no even numbers." 
            << endl;
   }
}

References:

  • Http://msdn.microsoft.com/en-us/library/dd293603.aspx
  • Http://msdn.microsoft.com/en-us/library/dd293599.aspx

Author: gnuhpc

Source: http://www.cnblogs.com/gnuhpc/

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.