zoukankan      html  css  js  c++  java
  • C++ 11学习(1):lambda表达式

    转载请注明,来自:http://blog.csdn.net/skymanwu

    #include <iostream>
    #include <vector>
    #include <functional>
    using namespace std;
    
    vector<function<int(int)>> v;
    
    // lambda使用function封装
    function<int(int)> f1(int k)
    {
    	return function<int(int)>([=](int x) -> int 
    	{
    		if(x > k)
    			return 1;
    		else if(x == k)
    			return 0;
    		else
    			return -1;
    	});
    }
    
    // 要使用lambda表达式作为参数,需用函数模版
    template<typename Lambda>
    void f2(Lambda l, int i) 
    {
    	cout<< l(i) <<endl;
    }
    
    int main()
    {
    	auto g = f1(10);
    	v.push_back(g);
    	for(vector<function<int(int)>>::iterator iter = v.begin(); iter != v.end(); ++iter)
    	{
    		cout << (*iter)(9) << endl;
    		cout << (*iter)(10) << endl;
    		cout << (*iter)(11) << endl;
    	}
    
    	int k = 10;
    
    	auto lambda = [=](int x) -> int 
    						{
    							if(x > k)
    								return 1;
    							else if(x == k)
    								return 0;
    							else
    								return -1;
    						};
    
    	k = 6;
    
    	f2(lambda, 8);
    
    	return 0;
    }

    输出结果:

    -1
    0
    1
    -1


    lambda 引入符:
    1. []             //不捕获任何外部变量
    2. [=]           //以值的形式捕获所有外部变量
    3. [&]          //以引用形式捕获所有外部变量
    4. [x, &y]     //x以传值形式捕获,y以引用形式捕获
    5. [=, &z]    //z以引用形式捕获,其余变量以传值形式捕获
    6. [&, x]      //x以值的形式捕获,其余变量以引用形式捕获

    例如上面的代码中,将“auto lambda = [=](int x) -> int”中的“=”改为"&",则k就是引用捕获,运行返回值则为1。


  • 相关阅读:
    codeforces 图论题目集(持续更新)
    整数快速幂
    Codeforces Codeforces Global Round 5 C2
    POJ 1061
    扩展欧几里德算法(数论)
    Codeforces Round #592 (Div. 2) 1224D
    Codeforces Round #582 (Div. 3) G. Path Queries
    2019 kickstart A轮 B 题
    P3379 【模板】最近公共祖先(LCA)
    bzoj 2002 分块
  • 原文地址:https://www.cnblogs.com/james1207/p/3283361.html
Copyright © 2011-2022 走看看