lambda表达式:[](){}
[capture list](argement list)mutable{function body}
[capture list]:
1.[x] 值传递x
2.[&x]引用传递x
3.[=]值传递所有的lambda外的变量值
4.[&]引用传递所有的lambda外的变量值
1 int test = 10; 2 auto lambda_val = [=] {return test + 1; }; 3 auto lambda_ref = [&] {return test + 1; }; 4 cout << lambda_val() <<" "<< lambda_ref() << endl; 5 test += 3; 6 cout << lambda_val() << " " << lambda_ref() << endl; 7 8 int val = 10; 9 auto mutable_val_lambda = [=]() mutable { val = 3; return val; }; 10 cout << mutable_val_lambda() << " "<< val << endl;
[=]值传递,传入的是x的初始值,不论从定义x到lambda用到x中间对x做了哪些值的操作,lambda中的x只可能是初始值。
[&]则继承了x的中间变化。
lambda的优点:
1 struct MyStruct 2 { 3 public: 4 MyStruct(int a, int b) :key(a), value(b) {} 5 6 int key; 7 int value; 8 9 }; 10 struct test 11 { 12 test(int key) :m_key(key) {} 13 void operator()(const MyStruct& pair) const 14 { 15 if (pair.key == m_key) 16 cout << pair.key << " " << pair.value << endl; 17 } 18 int m_key; 19 }; 20 void test_func(const vector<MyStruct>& vec, int key) 21 { 22 test m_test(key); 23 for_each(vec.begin(), vec.end(), m_test); 24 } 25 void lambda_func(const vector<MyStruct>& v, int key) 26 { 27 std::for_each(v.begin(), v.end(), [=](const MyStruct& v) 28 { 29 if (v.key == key) 30 cout << v.key << " " << v.value << endl; 31 } 32 ); 33 } 34 int main(int argc, char **argv) 35 { 36 MyStruct mytest[4] = { {10,2},{3,4},{10,4},{4,6} }; 37 vector<MyStruct> vec; 38 for (auto i = 0; i < 4; i++) 39 vec.emplace_back(mytest[i]); 40 test_func(vec, 10); 41 lambda_func(vec, 10); 42 return 1; 43 }
void test_func(const vector<MyStruct>& vec, int key)函数在此处的功能比较单一,如果m_test只是用在这里是浪费的。
如果用lambda实现:void lambda_func(const vector<MyStruct>& v, int key)不需要写m_test的实现。只要写lambda的表达式,毕竟我们只用一次。