Lambda表达式应用

1. 基本语法

[捕获列表](参数列表) -> 返回类型 {
    函数体 }

2. STL算法结合

// 自定义排序
vector<Student> students;
sort(students.begin(), students.end(), 
    [](const Student& a, const Student& b) {
   
        return a.score > b.score;  // 降序排列
    });

// 条件删除
vector<int> data {
   1,3,5,7,9};
data.erase(remove_if(data.begin(), data.end(),
                    [](int x) {
    return x%2 == 0; }), 
          data.end());

// 累积计算
double product = accumulate(data.begin(), data.end(), 1.0,
                           [](double a, double b) {
    return a * b; });

3. 捕获方式对比

捕获方式 效果 适用场景
[] 不捕获任何外部变量 纯算法操作
[=] 值捕获所有外部变量 需要变量快照
[&] 引用捕获所有外部变量 需要修改外部状态
[var] 值捕获特定变量 精确控制捕获变量
[this] 捕获当前类对象 类成员函数中的lambda

示例

class SensorMonitor {
   
    vector<double> readings;
    double threshold;
public:
    void checkReadings() {
   
        // 捕获this以访问成员变量
        int count = count_if(readings.begin(), readings.end(),
                            [this](double val) {
    
                                return val > this->threshold; 
                            });
        cout << "超过阈值的读数数量:" << count << endl;
    }
};

4. 泛型Lambda(C++14+)

auto print = [](const auto& item) {
     // 自动推导类型
    cout << item << endl;
};

vector<int> nums {
   1, 2, 3};
list<string> words {
   "apple", "banana"};
for_each(nums.begin(), nums.end(), print);
for_each(words.begin(), words.end(), print);

5. 延迟执行模式

// 创建闭包延迟执行
auto createLogger(const string& prefix) {
   
    return [prefix](const string& message) {
   
        cout << "[" << prefix << "] " << message << endl; 
    };
}

auto debugLog = createLogger("DEBUG");
auto errorLog = createLogger("ERROR");
debugLog("System initialized");
errorLog("Connection lost");

常见陷阱与解决方案

  1. Lambda悬空引用

    function<void()> createCallback() {
         
     int localVar = 42;
     // return [&localVar]() { ... };  // 危险!局部变量将被销毁
     return [localVar]() {
          ... };     // 正确:值捕获
    }
  2. 类型推导问题

    auto lambda = [](auto x, auto y) {
          return x + y; };
    // 明确返回类型避免意外结果
    auto safeLambda = [](auto x, auto y) -> decltype(x+y) {
          return x + y; };
posted @ 2025-11-03 08:55  kang_ms  阅读(4)  评论(0)    收藏  举报