栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++11中Lambda的使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++11中Lambda的使用

C++11中Lambda的使用

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

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


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

#include 
#include 
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 
#include 
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 
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 
using namespace std;
template
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 
#include 
using namespace std;
int foo(function 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;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1027031.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号