C++ Lambda Expressions: Getting Started Guide, Syntax, and Application Scenarios

Introduction:

Lambda expressions are a powerful feature introduced in C++11 that simplify code, improve readability, and support a functional programming style. This article will introduce the basic syntax, usage and applicable scenarios of Lambda expressions in detail, suitable for C++ entry-level readers.

1. Introduction to Lambda Expressions

Lambda expressions are a type of anonymous function that can be used where a function object is expected without defining a separate function. Lambda expressions have a concise syntax, can capture external variables, and have flexible application scenarios.

2. Basic syntax of Lambda expression

The basic syntax of a Lambda expression is as follows:

[capture-list](parameter-list) -> return-type {
    
     
    // 函数体 
}

capture-list: A list of captured external variables . Can be an empty list ([]) or a list containing one or more variables. Capture methods include value capture (=), reference capture (&), and mixed capture (=, &).
parameter-list: function parameter list. Like a normal function definition, can be empty or contain one or more parameters.
return-type: function return type. The return type can be specified as desired, or can be automatically inferred using the auto keyword.
Function body: the actual code logic of the Lambda expression.

3. Sample code for Lambda expressions

Here is a simple example showing the basic usage of Lambda expressions:

#include <iostream>

int main() {
    
    
    // 定义 Lambda 表达式并计算两个整数的差
    int a = 10;
    int b = 5;
    int result = [&a, b]() -> int {
    
    
        return a - b;
    }();

    // 打印结果
    std::cout << "Difference: " << result << std::endl;

    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    
    
    std::vector<int> numbers = {
    
     1, 2, 3, 4, 5 };

    // 使用 Lambda 表达式打印向量中的所有元素
    std::for_each(numbers.begin(), numbers.end(), [](int n) {
    
    
        std::cout << n << " ";
    });

    // 使用 Lambda 表达式计算向量中的所有元素之和
    int sum = 0;
    std::for_each(numbers.begin(), numbers.end(), [&sum](int n) {
    
    
        sum += n;
    });

    std::cout << "Sum: " << sum << std::endl;

    return 0;
}

In the above code, the first Lambda expression is used to print all elements in the vector, and the second Lambda expression is used to calculate the sum of all elements in the vector.

4. Application Scenarios of Lambda Expressions

Lambda expressions are useful in many scenarios, including:

4.1 STL algorithm

When using STL (Standard Template Library) algorithms, Lambda expressions can be passed to algorithm functions as predicates to simplify code writing, such as std::for_each in the sample code.

4.2 Sorting and comparing

Lambda expressions can be used to implement custom sorting and comparison functions, for example using std::sort or the sort method of custom containers.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    
    
    std::vector<int> numbers = {
    
     5, 2, 8, 1, 3 };

    // 使用 Lambda 表达式进行排序(升序)
    std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
    
    
        return a < b;
    });

    // 打印排序后的结果
    for (int num : numbers) {
    
    
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

In the above code, the Lambda expression is used as the predicate of the std::sort algorithm to sort the elements in the vector in ascending order.

4.3 Event Handling

In event processing, Lambda expressions can be used to define event handlers to make code more concise and readable.

#include <iostream>
#include <functional>

int main() {
    
    
    // Lambda 表达式作为事件处理函数
    std::function<void()> eventHandler = []() {
    
    
        std::cout << "Event occurred!" << std::endl;
    };

    // 模拟事件触发
    eventHandler();

    return 0;
}

In the above code, the Lambda expression is used as an event handler function, and when the event is triggered, the Lambda expression will be invoked.

in conclusion

Lambda expressions are a powerful feature of C++ that provide a concise and flexible way to define anonymous functions. This article introduces the basic syntax and usage of Lambda expressions, and provides sample codes and application scenarios. By properly using Lambda expressions, you can simplify code, improve readability, and achieve more flexible and efficient functions in different programming tasks.

Please note that the above sample code is for demonstration purposes only, please make appropriate modifications and error handling according to specific needs in actual use.

Guess you like

Origin blog.csdn.net/qq_46017342/article/details/131586852