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
原创粉丝点击