版权声明:本文为博主原创文章,未经博主允许不得转载。
这次主要介绍C++11的Lambda语法,一个非常给力的语法
1.组成 : [...导入符号](...参数)mutable(可改写) throwSpec(抛出异常) ->retType(返回值){...}
2.最简单的Lamdba
#include <iostream> int main(int argc, const char * argv[]) { [] { std::cout<< "hello lambda" <<std::endl; } (); return 0; }
输出结果
3.重新定义
#include <iostream> int main() { auto l =[] { std::cout<< "hello lambda111" <<std::endl; } ; l();//调用 return 0; }
输出结果
4.获取外部变量
int main() { //by value int id = 0; auto f = [id]() mutable{ std::cout<<"id = "<<id<<std::endl; ++id; }; id = 42; f(); f(); f(); return 0; }
输出结果
可能会很诧异为啥是输出结果为啥是0,1,2,因为传入的外界变量方式是by value,所以外界的id改变 不会改变lambda内的 id
引用传参
#include <iostream> int main() { //by reference int id = 0; auto g = [&id]() mutable{ std::cout<<"id = "<<id<<std::endl; id++; }; id = 10; g(); g(); g(); return 0; }
输出结果
5.带参数
#include <iostream> int main() { //by reference int id = 0; auto g = [&id](int parm) mutable{ std::cout<<"id = "<<id<<std::endl; std::cout<<"parm = "<<parm<<std::endl; id++; }; id = 10; g(7); g(8); g(9); return 0; }
输出结果
6.有返回值
#include <iostream> int main() { //by reference int id = 0; auto g = [&id](int parm) mutable{ std::cout<<"id = "<<id<<std::endl; std::cout<<"parm = "<<parm<<std::endl; return parm+id; }; id = 10; int tmp = g(9); std::cout<< "tmp = " << tmp << std::endl; return 0; }
输出结果
7.使代码简化
vector<int> vi{1,2,3,4,5,6,7,8,9,10}; int x = 2; int y = 9; vi.erase(remove_if(vi.begin(), vi.end(), [x,y](int n){return x<=n && n<=y;}),vi.end()); for(auto i:vi) cout<<i<<endl;
上面这段代码与下面代码意义相同
class ABC_Test_14 { public: ABC_Test_14(int a ,int b) :m_a(a),m_b(b){} bool operator()(int n) const { return m_a < n && n < m_b; } private: int m_a; int m_b; }; ... vi.erase(remove_if(vi.begin(), vi.end(), ABC_Test_14(x,y)),vi.end());
如有错误请指正.
参照<<侯捷 C++新标准 C++11>>