C++25、lambda表达式
来源:互联网 发布:遗传算法区域描述器 编辑:程序博客网 时间:2024/06/03 06:08
一个lambda就是一个可调用的代码单元,可以认为是一个内联函数或者是一个仿函数一般的存在。下面是一些常用的例子(第一个例子的代码来自C++primer附带源码,个人作为了解lambda只用,仅略作修改。第二个例子是实际中代码中可能见到的样子。):
#include <vector>#include <string>#include <iostream>using std::cout; using std::endl; using std::vector; using std::string;// five functions illustrating different aspects of lambda expressionsvoid fcn1(){size_t v1 = 42; // local variable// copies v1 into the callable object named fauto f = [v1] { return v1; };v1 = 0;auto j = f(); // j is 42; f stored a copy of v1 when we created itcout <<"fcn1 "<<" "<<j << endl;}void fcn2(){size_t v1 = 42; // local variable// the object f2 contains a reference to v1 auto f2 = [&v1] { return v1; };cout<<"fcn2 "<<" "<<f2()<<endl;v1 = 0;auto j = f2(); // j is 0; f2 refers to v1; it doesn't store itcout <<"fcn2 "<<" "<<j << endl;}void fcn3(){size_t v1 = 42; // local variable// f can change the value of the variables it capturesauto f = [v1] () mutable { return ++v1; };v1 = 0;auto j = f(); // j is 43cout <<"fcn3 "<<" "<<j << endl;}void fcn4(){size_t v1 = 42; // local variable// v1 is a reference to a nonconst variable// we can change that variable through the reference inside f2auto f2 = [&v1] { return ++v1; };v1 = 0;auto j = f2(); // j is 1cout <<"fcn4 "<<" "<<j << endl;}void fcn5(){ size_t v1 = 42;// p is a const pointer to v1 size_t* const p = &v1;// increments v1, the objet to which p points auto f = [p]() { return ++*p; }; auto j = f(); // returns incremented value of *p cout <<"fcn5 "<< v1 << " " << j << endl; // prints 43 43 v1 = 0; j = f(); // returns incremented value of *p cout << v1 << " " << j << endl; // prints 1 1}int main(){fcn1();fcn2();fcn3();fcn4();fcn5();return 0;}
当然我们也可以用在处理一些STL相关的代码中,极大地简化代码:
#include <iostream>#include <vector>#include <algorithm>using namespace std;void State(vector<int>&vec){int errors;int score;auto print = [&]{cout << "error:" << errors << endl<<"score:"<<score<<endl;};errors = 0;score = 100;for_each (vec.begin(), vec.end(), [&](int i){errors += i;score -= i;});print();}int main(){vector <int> vec(10);generate(vec.begin(), vec.end(), []{return rand() % 10; });State(vec);return 0;}
0 0
- 【c/c++】Lambda表达式
- C#--Lambda表达式
- C#:Lambda 表达式
- C++lambda表达式
- C++lambda表达式
- C# Lambda表达式
- C++:lambda表达式
- C#Lambda表达式
- 【c++】lambda表达式
- C++lambda表达式简记
- c#lambda表达式复习
- [C++]Lambda表达式简介
- 【C#】理解Lambda表达式
- 【C++】Lambda表达式
- C++lambda表达式
- C++Lambda表达式用法
- C++:lambda表达式
- 【C#】Lambda表达式
- 成绩排序
- JQuery判断数组中是否包含某个元素
- 脚本shell的使用
- poj 3251 Big Square
- Leetcode刷题记——11. Container With Most Water(装最多水的容器)
- C++25、lambda表达式
- CDH权限测试示例
- java 参数过滤,防止异常注入
- ntp错误:no server suitable for synchronization found
- SpringMVC+Maven+Hibernate+Modbus
- Android 沉浸式状态栏
- OpenStack命令集合
- ruby脚本统计git管理的修改过的文件,得到每个author写的代码行数
- Lint工具去除Android工程里不再需要的资源