欢迎来到程序员中文网!

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

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

时间:2026年08月12日 05:34:29 浏览:1

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


Lambda 是匿名函数对象,简洁且功能强大,广泛用于 STL 算法。


1. 基本语法


[capture](parameters) -> return_type { body }


#include <algorithm>
std::vector<int> nums = {1, 2, 3, 4};
// 过滤偶数
nums.erase(std::remove_if(nums.begin(), nums.end(), [](int n) { return n % 2 == 0; }), nums.end());

2. 捕获方式



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

  • [&]:引用捕获

  • [this]:捕获当前对象

  • [a, &b]:混合


int factor = 2;
auto multiply = [factor](int x) { return x * factor; };

3. 泛型 Lambda(C++14)


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

4. 存储 Lambda(使用 std::function)


std::function<int(int)> func = [](int x) { return x * 2; };

Lambda 是现代 C++ 编程的必备工具。