欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ Lambda 表达式与函数对象

时间:2026年08月12日 04:46:50 浏览:0

Lambda 基本语法


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

示例:


#include <algorithm>
#include <vector>

std::vector<int> nums = {1, 2, 3, 4, 5};

// 过滤偶数
auto it = std::remove_if(nums.begin(), nums.end(), [](int n) {
return n % 2 == 0;
});

// 捕获外部变量
int threshold = 3;
auto count = std::count_if(nums.begin(), nums.end(), [threshold](int n) {
return n > threshold;
});

捕获方式



  • [=]:值捕获(拷贝)

  • [&]:引用捕获

  • [this]:捕获当前对象

  • [a, &b]:混合捕获


class Processor {
int factor = 2;
public:
void run() {
auto func = [*this](int x) { return x * factor; }; // C++17 值捕获 this
}
};

泛型 Lambda (C++14)


auto generic_add = [](auto a, auto b) { return a + b; };
std::cout << generic_add(3, 4) << std::endl; // 7
std::cout << generic_add(1.2, 3.4) << std::endl; // 4.6

Lambda 让 STL 算法变得极其灵活,是现代 C++ 不可或缺的特性。