lambda函数是c++11新增的内容
完整结构:
[capture_list](para_list)mutable exception->return_type{ func_body } [捕捉列表](形参列表)提示符 异常设定->返回类型{函数内容} mutable 是否可以修改捕获的传值变量,默认是const即不可修改 | 使用mutable时前面必须有(para_list)exception 异常设定匿名函数主要的作用是避免了为一个简短的函数过程创建一个函数,从而减少了标示符,降低了冲突的风险而且比较简洁
常用形式:
[capture_list](para_list)->{ func_body }简单示例:
#include <iostream> #include <algorithm> #include <string> using namespace std; int main(int argc, char const *argv[]) { string s = "asdfhjsakf"; sort(s.begin(), s.end(), [](char x, char y){ return x < y; }); cout << s << endl; } // aadffhjkss可以看到不用再另外写一个比较函数cmp了,直接使用匿名函数就更简单
[ ]中的捕获变量用法:
捕获形式说明[]不捕获[para, ...]以值传递的形式捕获变量[this]以值传递的形式捕获this指针[=]以值传递的形式捕获所有的外部变量[&]以引用传递的形式捕获所有外部变量[&, a]以值传递的形式捕获a,以引用传递的形式捕获其他外部变量[=, &a]以引用的形式捕获a,以值传递的形式捕获其他外部变量使用捕获变量的例子:
#include <iostream> #include <algorithm> #include <string> using namespace std; int main(int argc, char const *argv[]) { string s = "asdfhjsakf"; int a = 1000; auto add = [&s, a](){ s += to_string(a); }; add(); cout << s << endl; } // asdfhjsakf1000上面使用引用传递的方式传递了s,结果输出s时原本的值已经发生了变化
使用值传递的方式传递了a,是将a复制进了lambda表达式中
1. 使用mutable的情况
还是上面的例子,不过此时在匿名函数中尝试修改传入a的值,如果不加mutable,编译报错:
加上mutable允许修改捕获参数之后就正常输出
#include <iostream> #include <algorithm> #include <string> using namespace std; int main(int argc, char const *argv[]) { string s = "asdfhjsakf"; int a = 1000; auto add = [&s, a]()mutable { a = 999; s += to_string(a); }; add(); cout << s << endl; } asdfhjsakf999加上mutable允许修改捕获参数之后就正常输出
2. 使用return_type的情况
可以定义返回类型为double
#include <iostream> #include <algorithm> #include <string> #include <cstdio> using namespace std; int main(int argc, char const *argv[]) { float r = 12.7; float PI = 3.14; auto lambda = [PI](float x)->double{ return PI * x * x; }; printf("%16.16lf\n", lambda(r)); } // 506.45062255859375003. 当形式参数当定义过长当时候,可以使用auto来自动获得形式参数的类型
#include <iostream> #include <algorithm> #include <string> #include <cstdio> using namespace std; int main(int argc, char const *argv[]) { float PI = 3.14; auto lambda = [PI](auto x)->double{ return PI * x * x; }; printf("%16.16lf\n", lambda(10)); } // 314.0000000000000000参考:
https://blog.csdn.net/sinat_35678407/article/details/82794514
https://blog.csdn.net/xiaoguyin_/article/details/79798362
https://blog.csdn.net/weixin_36750623/article/details/84860652