C++ Landscape in the Fog 8: Lambda Expressions

The last C++ blog was Long Long ago, and I mentioned looking at Lambda expressions . . The author first came into contact with Lambda expressions when I was learning the Python language. At that time, I didn’t quite understand the essence of this expression method. Later, I came into contact with the combination of Scala and Java8’s chain invocation with Lambda, and I couldn’t help myself. So borrow the content of the previous closure. Let's take a complete look at Lambda expressions in C++.

1. What is a Lambda expression?

Lambda expressions are an important syntactic structure of functional programming.
Lambda expression (lambda expression) is very simple to say, it is an anonymous function, that is, a function without a function name. Lambda expressions can represent closures. (Note that it is different from the traditional sense of mathematics). ( Essentially a Lambda expression operates on a function as an anonymous object )

In fact, a programming language that lacks Lambda expressions does not affect the logical expression of the programming language. The core of Lambda expressions is to provide a useful syntactic sugar: a function can be defined directly without separating the definition function from the grammar content. Helps express logic in a more compact way. If you need to define a function that happens to be used only once, and then you need to define a name for it, as a lazy programmer, you need to move out of Lambda expressions. Let's look at a piece of Python code to filter even numbers in a list. This is a very simple requirement. Let's first look at the way without using Lambda expressions:

def isOdd(n):
    return n & 1;

nums = [1,2,3,4,5,6]
nums = filter(isOdd,nums)

Obviously, it is very troublesome to define an additional code logic here: first, you need to jump out of the running code to view the code of the defined isOdd function, and secondly, the filtering logic that needs to be implemented here is very simple. This situation is the most suitable scenario for using lambda expressions. Let's take a look at how lambda expressions optimize the above code:

nums = [1,2,3,4,5,6]
nums = filter(lambda x:x & 1,nums)

Well, it is very elegant to use lambda expressions to solve the same needs, and the expression is very clear:
the following usage scenarios are suitable for lambda expressions:

  • (1) The logic defined by the code is more compactly connected with the execution logic.
  • (2) The code is more concise.
  • (3) Ability to support closures.

2. Lambda expressions in C++

C++ adds the syntax structure of Lambda expressions in C++11. The syntax structure of Lambda is as follows:

[capture](parameters)->return-type {body}

Next, let's analyze what each part represents and how to use it:

  • [capture]
    capture represents the capture of external variables. The author has an example of this method in the content of the closing package in the previous article. Variable capture is the most complicated part of Lambda expressions. Let’s take a look. Look at the meaning of the various representations:
  • [] does not capture any variables ( but must be written, the compiler recognizes lambda expressions by capturing structures )
  • [&} captures all variables in the outer scope by reference
  • [=] Capture all variables in the outer scope by copying
    ( the above two methods are too rude. In practice, try to use the following mode to limit the referenced variables, do not arbitrarily quote )
  • [x, &y] x is passed by value, y is passed by reference
  • [this] intercepts the this pointer in the current class. This option is added by default if & or = is already used.

As you can see, the syntax structure of [capture] captures external variables and implements closures in this way .

  • The (parameters)
    part is very simple, similar to the parameter list used by a normal function, and there is no difference in how it is used.

  • ->return-type
    explicitly specifies the return value type returned by the lambda expression. It is generally recommended not to write here, because the C++ compiler will infer the return value type of the function by type inference, and the preceding -> can also be omitted.

  • {body}
    The function body enclosed in curly braces has nothing to say, it is the part that implements the function logic.

Similarly, let's take a look at how the code for filtering even numbers implemented in python above is implemented in C++:

    vector<int> nums = {1,2,3,4,5,6,7};
    vector<int> newNums(nums.size());
    
    auto last = copy_if(nums.cbegin(), nums.cend(),newNums.begin(),[](int x){return !(x & 1);});
    for_each(newNums.begin(), last, [](int x) {
        cout << x << endl;
    });

Compared with the python implementation, it seems that the C++ implementation version does not simplify the application logic much because of the lack of chained calls, but looks a little messy. But this does not prevent us from using Lambda expressions in appropriate places to optimize our code structure.

3. Other languages ​​and Lambda expressions


  • The Lambda expression that Java Java finally came out in the Java 8 version is really a personal favorite, and I personally feel that Java 8 has a profound impact on the Java language. Let's see how the above logic is implemented in Java:

    public static void main(String[] args) {
        int[] nums = {1,2,3,4,5,6,7};
        IntStream.of(nums).filter((x)->{return (x & 1) == 1;}).forEach(System.out::println);
    }

    Compared with C++, it is much more elegant, and the parameter type can also perform type inference, which is indeed more friendly to programmers.

Frankly speaking: Java is a very lucky language, and it has been on the wave of mobile development and big data. However, with the lawsuit between Google and Oracle, it is not known whether Java will continue its current strong position in the future.

  • Golang
    doesn't have Lambda expressions, what we want is concise and clear, don't follow Geek's stuff.

4. Summary

I feel that the dry goods in this article are a little less, and the complaints are a little more, sorry ha~~~. I will talk to you about Lambda expressions in C++ here. I hope you can use it well in actual Coding to simplify your code structure as much as possible.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325076675&siteId=291194637