c++ function &n lamda表达式 使用实例

function 定义一个可调用实体

lamda相当于闭包,匿名函数,OC中的block

下面是简答使用的一个demo

function myfunc;//入参是int,int,出参是int

myfunc = ->int{

return x + y;

};//给func赋值

cout << myfunc(10, 20) << endl;//调用

#include "stdafx.h"


#include <iostream>
#include <map>
#include <functional>
using namespace std;

// 普通函数
int add(int i, int j) { return i + j; }
// lambda表达式
auto mod = [](int i, int j) {return i % j; };
// 函数对象类
struct divide
{
    int operator() (int denominator, int divisor)
    {
        return denominator / divisor;
    }
};

///////////////////////////SubMain//////////////////////////////////
int main(int argc, char *argv[])
{
    // 受限的map
    map<char, int(*)(int, int)> binops_limit;
    binops_limit.insert({ '+', add });
    binops_limit.insert({ '%', mod });
    // 错误    1    error C2664: “void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::initializer_list<std::pair<const _Kty,_Ty>>)”: 无法将参数 1 从“initializer-list”转换为“std::pair<const _Kty,_Ty> &&”
    // binops_limit.insert({ '%', divide() });

    // 更灵活的map
    map<char, function<int(int, int)>> binops =
    {
        { '+', add },
        { '-', minus<int>() },
        { '*', [](int i, int j) {return i *j; } },
        { '/', divide() },
        { '%', mod },
    };
    cout << binops['+'](10, 5) << endl;
    cout << binops['-'](10, 5) << endl;
    cout << binops['*'](10, 5) << endl;
    cout << binops['/'](10, 5) << endl;
    cout << binops['%'](10, 5) << endl;


    function <int(int, int)> myfunc;
    myfunc = [](int x,int y)->int{
        return x + y;
    };
    cout << myfunc(10, 20) << endl;
    system("pause");
    return 0;
}

ps:lamda捕获参数的方法

在Lambda表达式的函数体内,是不能够访问到外部的变量的,如果想要使用函数体外定义的变量,就需要将它们进行"捕获"

capture, =, [=,&], &, [this]

当我们不希望在捕获的时候将所有的变量都捕获的时候,我们可以使用如下的方

[=, &foo] 通过变量的拷贝捕获,但是用foo变量的引用捕获

[bar] 通过复制捕获,不要复制其他

[this] 捕获this指针对应成员

原文链接: https://www.cnblogs.com/hellozhuzi/p/5719926.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/237823

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午5:33
下一篇 2023年2月13日 下午5:33

相关推荐