#include <iostream>
#include <functional>
int main() {
// 定义一个匿名函数(lambda表达式)
auto lambda = [] (int x, int y) -> int {
return x + y;
};
// 使用匿名函数
int result = lambda(3, 4);
std::cout << "Result: " << result << std::endl;
// 匿名函数可以直接作为参数传递给其他函数
std::function<int(int, int)> func = lambda;
int anotherResult = func(5, 6);
std::cout << "Another Result: " << anotherResult << std::endl;
return 0;
}
[] 符号来定义匿名函数,也称为 lambda 表达式。[] 内可以捕获外部变量。(int x, int y) 是匿名函数的参数列表,-> int 指定了返回类型为 int。auto 类型的变量 lambda,然后像普通函数一样调用它。std::function 类型,并作为参数传递给其他函数或存储在变量中。希望这段代码和解释对你理解 C++ 中的匿名函数有所帮助!
上一篇:c++快速排序
下一篇:c++基本语法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站