C++ lambda表达式
Lambda表达式是一种简洁的方式来创建匿名函数,可以直接在函数调用的地方定义,主要用于简化代码。
Lambda表达式的基本语法如下:
[capture](parameters) -> return_type {
// function body
};
示例1:基本用法
在这个例子中,lambda表达式 [](int n) { std::cout << n << " "; } 被传递给 std::for_each 用来遍历并打印 numbers 中的每个元素。
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用lambda表达式打印vector中的元素
std::for_each(numbers.begin(), numbers.end(), [](int n) {
std::cout << n << " ";
});
std::cout << std::endl;
return 0;
}
示例2:捕获变量
Lambda表达式可以通过捕获列表 [capture] 捕获作用域中的变量。捕获方式包括按值捕获和按引用捕获。
#include <iostream>
int main() {
int a = 10;
int b = 20;
// 按值捕获a和b
auto lambda_value_capture = [a, b]() {
std::cout << "Value capture: " << a << ", " << b << std::endl;
};
lambda_value_capture();
// 按引用捕获a和b
auto lambda_reference_capture = [&a, &b]() {
std::cout << "Reference capture: " << a << ", " << b << std::endl;
};
lambda_reference_capture();
// 修改a和b的值
a = 30;
b = 40;
lambda_value_capture(); // 输出依旧是10, 20,因为是按值捕获
lambda_reference_capture(); // 输出是30, 40,因为是按引用捕获
return 0;
}
示例3:参数和返回值
Lambda表达式可以接受参数并返回值,参数和返回类型的语法与普通函数类似。
#include <iostream>
#include <functional>
int main() {
// 带参数和返回值的lambda表达式
std::function<int(int, int)> add = [](int x, int y) -> int {
return x + y;
};
int result = add(5, 3);
std::cout << "Result: " << result << std::endl; // 输出 Result: 8
return 0;
}
示例4:在STL算法中的应用
Lambda表达式经常用于STL算法中,例如 std::sort、std::transform 等。
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
// 使用lambda表达式排序
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a < b;
});
// 打印排序后的vector
std::for_each(numbers.begin(), numbers.end(), [](int n) {
std::cout << n << " ";
});
std::cout << std::endl; // 输出 1 2 5 5 6 9
return 0;
}
说明
- 捕获列表 [capture]:指定lambda表达式如何捕获外部变量。可以使用[=]捕获所有变量为值,[&]捕获所有变量为引用。
- 参数列表 (parameters):与普通函数参数列表一样。
- 返回类型 -> return_type:指定lambda表达式的返回类型,可省略。
- 函数体 { // function body }:定义lambda表达式的具体实现。