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

c++11 lambda 函数

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

c++11 lambda 函数

STL算法传递信息方式:函数指针、函数符 (函数对象) 和 lambda .

lambda 函数的使用示例:

vector numbers{1, 2, 3, 4, 5, 6};
int count3;
count3 = count_if(numbers.begin(), numbers.end(), [](int x) {
    return x % 3 == 0;
});

lambda 函数使用 [] 代替函数名(这就是匿名的由来)

可以不声明返回类型,当没有声明返回类型时,相当于使用 decltype 根据返回值推断。这里为 bool . 也可以声明返回类型,如下面代码所示:

count3 = count_if(numbers.begin(), numbers.end(), [](int x) -> bool {
    return x % 3 == 0;
});

也可以给 lambda 函数指定一个名称,如:

auto mod3 = [](int x){return x % 3 == 0;} // mod3 a name for the lambda
count1 = std::count_if(n1.begin(), n1.end(), mod3);
count2 = std::count_if(n2.begin(), n2.end(), mod3);

函数指针方法阻止内联,lambda 和 函数符不阻止内联。The relative efficiencies of the three approaches boils down to what the compiler chooses to inline. Here, the function pointer approach is handicapped by the fact that compilers traditionally don’t inline a function that has its address taken because the concept of a function address implies a non-inline function.With functors and lambdas, there is no apparent contradiction with inlining.

lambda 有一些额外的功能。具体地说,lambda 可访问作用域内的任何动态变量;要捕获要使用的变量,可将其名称放在中括号内。如果只指定了变量名,如[z],将按值访问变量;如果在名称前加上&,如 [&count],将按引用访问变量。[&]让您能够按引用访问所有动态变量,而[=]让您能够按值访问所有动态变量。还可混合使用这两种方式,例如,[ted, &ed] 让您能够按值访问 ted 以及按引用访问ed,[&, ted] 让您能够按值访问 ted 以及按引用访问其他所有动态变量,[=,&ed]让您能够按引用访问 ed 以及按值访问其他所有动态变量。

综上,lambda 函数有以下特性:

  • lambda 函数使用 [] 代替函数名
  • 可以不声明返回类型(当没有声明返回类型时,相当于使用 decltype 根据返回值推断)
  • 可以给 lambda 函数指定一个名称
  • lambda 不阻止内联
  • 可在[] 自定义按值和/或按引用访问作用域内的任何动态变量。

参考资料

[1] C++.Primer.Plus.6th.Edition

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/928766.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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