C++11中Lambda的使用

C++11中Lambda的使用

关于lambda函数,百度百科中的解释是这样的:
Lambda 表达式(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。Lambda表达式可以表示闭包(注意和数学传统意义上的不同)。

#include <iostream>
using namespace std;
int main() {
	auto f = [](int x){ return x * x; };
	cout << f(20) << endl;
	return 0;
}
lambda的格式:
[捕获列表]<模板声明>(参数列表)mutable 异常说明->类型{函数体}

在这里插入图片描述
在这里插入图片描述

对于sort排序中,需要用到仿函数,根据入参进行排序,仿函数返回bool

#include <iostream>
#include <algorithm>
using namespace std;
bool fun(const int &a, const int &b) {
    if ((a % 2 == 1) && (b % 2 == 0))
        return true;
    if (a < b) return true;
    return false;
}
int main() {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    sort(a, a + 10, fun);
    for (int i = 0; i < 10; i++)
        cout << a[i] << ' ';
// 输出:1 3 5 7 9 2 4 6 8 10
    return 0;
}

使用lambda函数实现

auto f = [](const int &a, const int &b){
        if ((a % 2 == 1) && (b % 2 == 0))
            return true;
        if (a < b) return true;
        return false;
    }
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    sort(a, a + 10, [](const int &a, const int &b){
        if ((a % 2 == 1) && (b % 2 == 0))
            return true;
        if (a < b) return true;
        return false;
    });
    for (int i = 0; i < 10; i++)
        cout << a[i] << ' ';
// 输出:1 3 5 7 9 2 4 6 8 10
    return 0;
}
#include <iostream>
using namespace std;
int foo(int (*f)(int), int x) {
	return f(x);
}
int main() {
	cout << foo([](int a)->int{ return a * 5 + 7; }, 2) << endl;
	// 输出 17,一切正常
	int Integer = 123;
	cout << foo([Integer](int a)->int{ return a * 5 + Integer; }, 2) << endl;
	// 编译错误
return 0;
}

[](int a)->int{ return a * 5 + 7; }可以隐式转换为int (*)(int)类型来传递,但添加了捕获参数的lambda函数不能转换为函数指针
解决方法:
使用模板参数(因为lambda的本质是一个临时对象)。
使用functional头文件封装的std::function类型。
正确改法:

模板参数


#include <iostream>
using namespace std;
template<class Fn>
int foo(Fn f, int x) {
	return f(x);
}
int main() {
	cout << foo([](int a)->int{ return a * 5 + 7; }, 2) << endl;
	// 输出 17
	int Integer = 123;
	cout << foo([Integer](int a)->int{ return a * 5 + Integer; }, 2) << endl;
	// 输出 133
return 0;
}
std::function


#include <iostream>
#include <functional>
using namespace std;
int foo(function<int(int)> f, int x) {
	return f(x);
}
int main() {
	cout << foo([](int a)->int{ return a * 5 + 7; }, 2) << endl;
	// 输出 17
	int Integer = 123;
	cout << foo([Integer](int a)->int{ return a * 5 + Integer; }, 2) << endl;
	// 输出 133
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值