• < lambda表达式与包装器>——《C++高阶》


    目录

    1.lambda表达式

    1.1 C++98中的例子

    1.2 lambda表达式

     1.3 lambda表达式语法

    1. lambda表达式各部分说明

     2. 捕获列表说明

     1.4 函数对象与lambda表达式

     2.包装器

    2.1 function包装器

    2.2例题练习:

    逆波兰表达式:

    2.3 bind

    后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!

                                                                               ——By 作者:新晓·故知


    1.lambda表达式

    1.1 C++98中的例子

    在C++98中,如果想要对一个数据集合中的元素进行排序,可以使用std::sort方法。 
     

     

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. int main()
    6. {
    7. int array[] = { 4,1,8,5,3,7,0,9,2,6 };
    8. // 默认按照小于比较,排出来结果是升序
    9. std::sort(array, array + sizeof(array) / sizeof(array[0]));
    10. for (auto e : array)
    11. {
    12. cout << e << " ";
    13. }
    14. cout << endl;
    15. // 如果需要降序,需要改变元素的比较规则(使用仿函数)
    16. std::sort(array, array + sizeof(array) / sizeof(array[0]), greater<int>());
    17. for (auto e : array)
    18. {
    19. cout << e << " ";
    20. }
    21. cout << endl;
    22. return 0;
    23. }

    如果待排序元素为自定义类型,需要用户定义排序时的比较规则:

     

    1. struct Goods
    2. {
    3. public:
    4. string _name; // 名字
    5. double _price; // 价格
    6. int _evaluate; // 评价
    7. Goods(const char* str, double price, int evaluate)
    8. :_name(str)
    9. ,_price(price)
    10. ,_evaluate(evaluate)
    11. {}
    12. };
    13. struct ComparePriceLess
    14. {
    15. bool operator()(const Goods& gl, const Goods& gr)
    16. {
    17. return gl._price < gr._price;
    18. }
    19. };
    20. struct ComparePriceGreater
    21. {
    22. bool operator()(const Goods& gl, const Goods& gr)
    23. {
    24. return gl._price > gr._price;
    25. }
    26. };
    27. int main()
    28. {
    29. vector v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 3 }, { "菠萝", 1.5, 4 } };
    30. for (auto e : v)
    31. {
    32. cout << e._name << ":"<<" " << e._price << " " << e._evaluate<
    33. }
    34. cout << endl;
    35. sort(v.begin(), v.end(), ComparePriceLess());
    36. for (auto e : v)
    37. {
    38. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    39. }
    40. cout << endl;
    41. sort(v.begin(), v.end(), ComparePriceGreater());
    42. for (auto e : v)
    43. {
    44. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    45. }
    46. cout << endl;
    47. }
    随着C++语法的发展,人们开始觉得上面的写法太复杂了,每次为了实现一个algorithm算法, 都要重新去写一个类,如果每次比较的逻辑不一样,还要去实现多个类,特别是相同类的命名, 这些都给编程者带来了极大的不便。因此,在C++11语法中出现了Lambda表达式。

     

    1.2 lambda表达式

     

    1. int main()
    2. {
    3. vector v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 3 }, { "菠萝", 1.5, 4 } };
    4. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2){
    5. return g1._price < g2._price; });
    6. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
    7. return g1._price > g2._price; });
    8. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
    9. return g1._evaluate < g2._evaluate; });
    10. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
    11. return g1._evaluate > g2._evaluate; });
    12. }

     

    上述代码就是使用C++11中的lambda表达式来解决,可以看出lambda表达式实际是一个匿名函数。

     

    1. //lambda表达式举例:
    2. int main()
    3. {
    4. int a = 113, b = 6;
    5. //lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement }
    6. // 捕捉列表 参数列表 可变的 返回值类型 函数体
    7. //一般是局部匿名函数,也可以写到全局
    8. auto Add1 = [](int x, int y)->int {return x + y; };
    9. auto Add2 = [](int x, int y)->char {return x + y; };
    10. cout << Add1(a, b) << endl;
    11. cout << Add2(a, b) << endl;
    12. }

     1.3 lambda表达式语法

    lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement
    };

    1. lambda表达式各部分说明

    [capture-list] : 捕捉列表,该列表总是出现在lambda函数的开始位置,编译器根据[]来
    判断接下来的代码是否为lambda函数捕捉列表能够捕捉上下文中的变量供lambda
    函数使用
    (parameters):参数列表。与普通函数的参数列表一致,如果不需要参数传递,则可以
    连同()一起省略
    mutable:默认情况下,lambda函数总是一个const函数,mutable可以取消其常量
    性。使用该修饰符时,参数列表不可省略(即使参数为空)。

     

    ->returntype:返回值类型。用追踪返回类型形式声明函数的返回值类型,没有返回
    值时此部分可省略。返回值类型明确情况下,也可省略,由编译器对返回类型进行推
    {statement}:函数体。在该函数体内,除了可以使用其参数外,还可以使用所有捕获
    到的变量。
    注意:
    在lambda函数定义中,参数列表和返回值类型都是可选部分,而捕捉列表和函数体可以为
    。因此C++11中最简单的lambda函数为:[]{}; 该lambda函数不能做任何事情。
    1. int main()
    2. {
    3. // 最简单的lambda表达式, 该lambda表达式没有任何意义
    4. [] {};
    5. // 省略参数列表和返回值类型,返回值类型由编译器推导为int
    6. int a = 3, b = 4;
    7. [=] {return a + 3; };
    8. // 省略了返回值类型,无返回值类型
    9. auto fun1 = [&](int c) {b = a + c; };
    10. fun1(10)
    11. cout << a << " " << b << endl;
    12. // 各部分都很完善的lambda函数
    13. auto fun2 = [=, &b](int c)->int {return b += a + c; };
    14. cout << fun2(10) << endl;
    15. // 复制捕捉x
    16. int x = 10;
    17. auto add_x = [x](int a) mutable { x *= 2; return a + x; };
    18. cout << add_x(10) << endl;
    19. return 0;
    20. }
    通过上述例子可以看出,lambda表达式实际上可以理解为无名函数,该函数无法直接调
    用,如果想要直接调用,可借助auto将其赋值给一个变量。
    1. //lambda表达式举例:
    2. int main()
    3. {
    4. int a = 113, b = 6;
    5. //lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement };
    6. // 捕捉列表 参数列表 可变的 返回值类型 函数体
    7. //一般是局部匿名函数,也可以写到全局
    8. //auto Add1 = [](int x, int y)->int {return x + y; };
    9. //cout << Add1(a, b) << endl;
    10. cout << "a=:" << a << " " << "b=:" << b << endl;
    11. auto Swap1 = [](int& x, int& y)
    12. {
    13. int tmp = x;
    14. x = y;
    15. y = tmp;
    16. };
    17. Swap1(a, b);
    18. cout <<"a=:"<< a << " " <<"b=:" << b << endl;
    19. }

     

    1. //lambda表达式举例:
    2. int main()
    3. {
    4. int a = 113, b = 6;
    5. //lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement };
    6. // 捕捉列表 参数列表 可变的 返回值类型 函数体
    7. //一般是局部匿名函数,也可以写到全局
    8. //auto Add1 = [](int x, int y)->int {return x + y; };
    9. //cout << Add1(a, b) << endl;
    10. cout << "a=:" << a << " " << "b=:" << b << endl;
    11. //mutable:默认情况下,lambda函数总是一个const函数,mutable可以取消其常量性。
    12. //使用该修饰符时,参数列表不可省略(即使参数为空)。
    13. auto Swap2 = [a,b]()mutable
    14. {
    15. int tmp = a;
    16. a = b;
    17. b = tmp;
    18. };
    19. Swap2();
    20. cout << "a=:" << a << " " << "b=:" << b << endl;
    21. }

     

     

    1. //lambda表达式举例:
    2. int main()
    3. {
    4. int a = 113, b = 6;
    5. //lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement };
    6. // 捕捉列表 参数列表 可变的 返回值类型 函数体
    7. //一般是局部匿名函数,也可以写到全局
    8. //auto Add1 = [](int x, int y)->int {return x + y; };
    9. //cout << Add1(a, b) << endl;
    10. cout << "a=:" << a << " " << "b=:" << b << endl;
    11. //用引用的方式捕捉
    12. auto Swap2 = [&a, &b]
    13. {
    14. int tmp = a;
    15. a = b;
    16. b = tmp;
    17. };
    18. Swap2();
    19. cout << "a=:" << a << " " << "b=:" << b << endl;
    20. }

     2. 捕获列表说明

    捕捉列表描述了上下文中那些数据可以被lambda使用,以及使用的方式传值还是传引用
    [var]:表示值传递方式捕捉变量var
    [=]:表示值传递方式捕获所有父作用域中的变量(包括this)
    [&var]:表示引用传递捕捉变量var
    [&]:表示引用传递捕捉所有父作用域中的变量(包括this)
    [this]:表示值传递方式捕捉当前的this指针
    注意:
    a. 父作用域指包含lambda函数的语句块
    b. 语法上捕捉列表可由多个捕捉项组成,并以逗号分割
    比如:[=, &a, &b]:以引用传递的方式捕捉变量a和b,值传递方式捕捉其他所有变量
    [&,a, this]:值传递方式捕捉变量a和this,引用方式捕捉其他变量
    c. 捕捉列表不允许变量重复传递,否则就会导致编译错误
    比如:[=, a]:=已经以值传递方式捕捉了所有变量,捕捉a重复
    d. 在块作用域以外的lambda函数捕捉列表必须为空
    e. 在块作用域中的lambda函数仅能捕捉父作用域中局部变量,捕捉任何非此作用域或者
    非局部变量都
    会导致编译报错。
    f. lambda表达式之间不能相互赋值,即使看起来类型相同
    1. void (*PF)();
    2. int main()
    3. {
    4. auto f1 = [] {cout << "hello world" << endl; };
    5. auto f2 = [] {cout << "hello world" << endl; };
    6. // 此处先不解释原因,等lambda表达式底层实现原理看完后,大家就清楚了
    7. //f1 = f2;   // 编译失败--->提示找不到operator=()
    8. // 允许使用一个lambda表达式拷贝构造一个新的副本
    9. auto f3(f2);
    10. f3();
    11. // 可以将lambda表达式赋值给相同类型的函数指针
    12. PF = f2;
    13. PF();
    14. return 0;
    15. }
    传值、传引用捕捉全部对象举例:
    1. //lambda表达式举例:
    2. int main()
    3. {
    4. //lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement };
    5. // 捕捉列表 参数列表 可变的 返回值类型 函数体
    6. int c = 9, d = 8, e = 7, f = 6, g = 5;
    7. //1.传值捕捉全部对象
    8. auto Func1 = [=]
    9. {
    10. return c - d + e * f + g;
    11. };
    12. cout << Func1() << endl;
    13. //2.传引用捕捉全部对象
    14. auto Func2 = [&]
    15. {
    16. return c * d + e * f - g;
    17. };
    18. cout << Func2() << endl;
    19. }

     混合捕捉:

     

    1. //lambda表达式举例:
    2. int main()
    3. {
    4. //lambda表达式书写格式:[capture-list] (parameters) mutable -> return-type { statement };
    5. // 捕捉列表 参数列表 可变的 返回值类型 函数体
    6. int c = 9, d = 8, e = 7, f = 6, g = 5,ret;
    7. //3.混合捕捉全部对象
    8. auto Func3 = [c,d,&ret]
    9. {
    10. ret = c + d;
    11. };
    12. Func3();
    13. cout <
    14. //4.ret传引用捕捉,其他全部传值捕捉
    15. auto Func4 = [=,&ret]
    16. {
    17. ret= c - d + e * f + g;
    18. };
    19. Func4();
    20. cout << ret << endl;
    21. }

    1. struct Goods
    2. {
    3. //结构体成员默认为公有
    4. //如果是class,就需要写一个Get函数,通过Get函数访问私有成员
    5. string _name; // 名字
    6. double _price; // 价格
    7. int _evaluate; // 评价
    8. Goods(const char* str, double price, int evaluate)
    9. :_name(str)
    10. , _price(price)
    11. , _evaluate(evaluate)
    12. {}
    13. };
    14. struct ComparePriceLess
    15. {
    16. bool operator()(const Goods& gl, const Goods& gr)
    17. {
    18. return gl._price < gr._price;
    19. }
    20. };
    21. struct ComparePriceGreater
    22. {
    23. bool operator()(const Goods& gl, const Goods& gr)
    24. {
    25. return gl._price > gr._price;
    26. }
    27. };
    28. int main()
    29. {
    30. vector v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 3 }, { "菠萝", 1.5, 4 } };
    31. //lambda表达式使意图简化、清晰
    32. sort(v.begin(), v.end(), ComparePriceLess());
    33. auto ComparePriceLess = [](const Goods& g1, const Goods& g2) {return g1._price < g2._price; };
    34. //或者直接省去对象名:ComparePriceLess。sort会自动推导类型。
    35. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {return g1._price < g2._price; });
    36. return 0;
    37. }

     

     

    1. struct Goods
    2. {
    3. //结构体成员默认为公有
    4. //如果是class,就需要写一个Get函数,通过Get函数访问私有成员
    5. string _name; // 名字
    6. double _price; // 价格
    7. int _evaluate; // 评价
    8. Goods(const char* str, double price, int evaluate)
    9. :_name(str)
    10. , _price(price)
    11. , _evaluate(evaluate)
    12. {}
    13. };
    14. struct ComparePriceLess
    15. {
    16. bool operator()(const Goods& gl, const Goods& gr)
    17. {
    18. return gl._price < gr._price;
    19. }
    20. };
    21. struct ComparePriceGreater
    22. {
    23. bool operator()(const Goods& gl, const Goods& gr)
    24. {
    25. return gl._price > gr._price;
    26. }
    27. };
    28. int main()
    29. {
    30. vector v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, 3 }, { "菠萝", 1.5, 4 } };
    31. for (auto e : v)
    32. {
    33. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    34. }
    35. cout << endl;
    36. //lambda表达式使意图简化、清晰
    37. sort(v.begin(), v.end(), ComparePriceLess());
    38. auto ComparePriceLess = [](const Goods& g1, const Goods& g2) {return g1._price < g2._price; };
    39. for (auto e : v)
    40. {
    41. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    42. }
    43. cout << endl;
    44. //或者直接省去对象名:ComparePriceLess。sort会自动推导类型。
    45. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {return g1._price < g2._price; });
    46. for (auto e : v)
    47. {
    48. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    49. }
    50. cout << endl;
    51. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {return g1._price > g2._price; });
    52. for (auto e : v)
    53. {
    54. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    55. }
    56. cout << endl;
    57. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {return g1._evaluate < g2._evaluate; });
    58. for (auto e : v)
    59. {
    60. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    61. }
    62. cout << endl;
    63. sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {return g1._evaluate > g2._evaluate; });
    64. for (auto e : v)
    65. {
    66. cout << e._name << ":" << " " << e._price << " " << e._evaluate << endl;
    67. }
    68. cout << endl;
    69. return 0;
    70. }

    调试时,如果没有显示lambda的调试信息,可能是因为进入的是lambda的定义,而非执行体!

    lambda表达式定义的是一个对象!

    1. void (*PF)();
    2. int main()
    3. {
    4. auto f1 = [] {cout << "hello world" << endl; };
    5. auto f2 = [] {cout << "hello world" << endl; };
    6. //f1 = f2;   // 编译失败--->提示找不到operator=() 。lambda底层其实是一个仿函数
    7. // 允许使用一个lambda表达式拷贝构造一个新的副本
    8. auto f3(f2);
    9. f3();
    10. // 可以将lambda表达式赋值给相同类型的函数指针
    11. PF = f2;
    12. PF();
    13. return 0;
    14. }

     f1和f2 是两个对象,底层生成的是两个类型的仿函数,因此这两个对象不能相互赋值!                

    每个lambda都会生成一个仿函数类型,lambda仿函数的名称是编译器取得(只是这个名称对于用户是隐藏的),而自己定义的函数对象的名称是自己取得!

     1.4 函数对象与lambda表达式

    函数对象,又称为仿函数,即可以想函数一样使用的对象,就是在类中重载了operator()运算符的 类对象。
    1. class Rate
    2. {
    3. public:
    4. Rate(double rate) : _rate(rate)
    5. {}
    6. double operator()(double money, int year)
    7. {
    8. return money * _rate * year;
    9. }
    10. private:
    11. double _rate;
    12. };
    13. int main()
    14. {
    15. // 函数对象
    16. double rate = 0.49;
    17. Rate r1(rate);
    18. r1(10000, 2);
    19. // lamber
    20. auto r2 = [=](double monty, int year)->double {return monty * rate * year;
    21. };
    22. r2(10000, 2);
    23. return 0;
    24. }
    '
    运行

    从使用方式上来看,函数对象与lambda表达式完全一样。

    函数对象将rate作为其成员变量,在定义对象时给出初始值即可,lambda表达式通过捕获列表可以直接将该变量捕获到。
    实际在底层编译器对于lambda表达式的处理方式,完全就是按照函数对象的方式处理的,即:如果定义了一个lambda表达式,编译器会自动生成一个类,在该类中重载了operator()。

     

    定义一个lambda,编译器会在底层生成一个仿函数。再去调用这个生成色仿函数。 

     2.包装器

    2.1 function包装器

    function包装器 也叫作适配器。C++中的function本质是一个类模板,也是一个包装器。
    那么我们来看看,我们为什么需要function呢?
    1. ret = func(x);
    2. // 上面func可能是什么呢?那么func可能是函数名?函数指针?函数对象(仿函数对象)?也有可能
    3. //是lamber表达式对象?所以这些都是可调用的类型!如此丰富的类型,可能会导致模板的效率低下!
    4. //为什么呢?我们继续往下看
    5. template<class F, class T> T useF(F f, T x) {
    6. static int count = 0;
    7. cout << "count:" << ++count << endl;
    8. cout << "count:" << &count << endl;
    9. return f(x);
    10. }
    11. double f(double i) {
    12. return i / 2;
    13. }
    14. struct Functor
    15. {
    16. double operator()(double d)
    17. {
    18. return d / 3;
    19. }
    20. };
    21. int main()
    22. {
    23. // 函数名
    24. cout << useF(f, 11.11) << endl;
    25. // 函数对象
    26. cout << useF(Functor(), 11.11) << endl;
    27. // lamber表达式
    28. cout << useF([](double d)->double { return d / 4; }, 11.11) << endl;
    29. return 0;
    30. }

     

     

    通过上面的程序验证,我们会发现useF函数模板实例化了三份。
    包装器可以很好的解决上面的问题
    1. std::function在头文件
    2. // 类模板原型如下
    3. template <class T> function;     // undefined
    4. template <class Ret, class... Args>
    5. class function<Ret(Args...)>;
    6. 模板参数说明:
    7. Ret: 被调用函数的返回类型
    8. Args…:被调用函数的形参
    1. // 使用方法如下:
    2. #include
    3. int f(int a, int b)
    4. {
    5. return a + b;
    6. }
    7. struct Functor
    8. {
    9. public:
    10. int operator() (int a, int b)
    11. {
    12. return a + b;
    13. }
    14. };
    15. class Plus
    16. {
    17. public:
    18. //静态的包装后就能用
    19. static int plusi(int a, int b)
    20. {
    21. return a + b;
    22. }
    23. //非静态的含有this指针,包装后需要加上类名
    24. double plusd(double a, double b)
    25. {
    26. return a + b;
    27. }
    28. };
    29. int main()
    30. {
    31. // 函数名(函数指针)
    32. std::function<int(int, int)> func1 = f;
    33. cout << func1(1, 2) << endl;
    34. // 函数对象
    35. std::function<int(int, int)> func2 = Functor();
    36. cout << func2(1, 2) << endl;
    37. // lamber表达式
    38. std::function<int(int, int)> func3 = [](const int a, const int b)
    39. {return a + b; };
    40. cout << func3(1, 2) << endl;
    41. // 类的成员函数
    42. std::function<int(int, int)> func4 = &Plus::plusi;
    43. cout << func4(1, 2) << endl;
    44. std::function<double(Plus, double, double)> func5 = &Plus::plusd;
    45. cout << func5(Plus(), 1.1, 2.2) << endl;
    46. return 0;
    47. }

     

    有了包装器,如何解决模板的效率低下,实例化多份的问题呢?

    1. #include
    2. template<class F, class T> T useF(F f, T x)
    3. {
    4. static int count = 0;
    5. cout << "count:" << ++count << endl;
    6. cout << "count:" << &count << endl;
    7. return f(x);
    8. }
    9. double f(double i)
    10. {
    11. return i / 2;
    12. }
    13. struct Functor
    14. {
    15. double operator()(double d)
    16. {
    17. return d / 3;
    18. }
    19. };
    20. int main()
    21. {
    22. // 函数名
    23. std::function<double(double)> func1 = f;
    24. cout << useF(func1, 11.11) << endl;
    25. // 函数对象
    26. std::function<double(double)> func2 = Functor();
    27. cout << useF(func2, 11.11) << endl;
    28. // lamber表达式
    29. std::function<double(double)> func3 = [](double d)->double { return d / 4; };
    30. cout << useF(func3, 11.11) << endl;
    31. return 0;
    32. }

    总结:

    可调用的对象:

    1.函数指针

    2.仿函数

    3.lambda

    2.2例题练习:

    逆波兰表达式:

    1. class Solution
    2. {
    3. public:
    4. int evalRPN(vector& tokens)
    5. {
    6. stack<int> st;
    7. for (const auto& str : tokens)
    8. {
    9. if (str == "+" || str == "-"
    10. || str == "*" || str == "/")
    11. {
    12. int right = st.top();
    13. st.pop();
    14. int left = st.top();
    15. st.pop();
    16. switch (str[0])
    17. {
    18. case '+':
    19. st.push(left + right);
    20. break;
    21. case '-':
    22. st.push(left - right);
    23. break;
    24. case '*':
    25. st.push(left * right);
    26. break;
    27. case '/':
    28. st.push(left / right);
    29. break;
    30. default:
    31. break;
    32. }
    33. }
    34. else
    35. {
    36. st.push(stoi(str));
    37. }
    38. }
    39. return st.top();
    40. }
    41. };

     

    1. class Solution {
    2. public:
    3. int evalRPN(vector& tokens) {
    4. stack<int> st;
    5. for (auto& str : tokens)
    6. {
    7. if (str == "+" || str == "-" || str == "*" || str == "/")
    8. {
    9. int right = st.top();
    10. st.pop();
    11. int left = st.top();
    12. st.pop();
    13. switch (str[0])
    14. {
    15. case '+':
    16. st.push(left + right);
    17. break;
    18. case '-':
    19. st.push(left - right);
    20. break;
    21. case '*':
    22. st.push(left * right);
    23. break;
    24. case '/':
    25. st.push(left / right);
    26. break;
    27. }
    28. }
    29. else
    30. {
    31. // 1、atoi itoa
    32. // 2、sprintf scanf
    33. // 3、stoi to_string C++11
    34. st.push(stoi(str));
    35. }
    36. }
    37. return st.top();
    38. }
    39. };
    40. // 使用包装器以后的玩法
    41. class Solution {
    42. public:
    43. int evalRPN(vector& tokens) {
    44. stack<int> st;
    45. mapint(int, int)>> opFuncMap =
    46. {
    47. { "+", [](int i, int j) {return i + j; } },
    48. { "-", [](int i, int j) {return i - j; } },
    49. { "*", [](int i, int j) {return i * j; } },
    50. { "/", [](int i, int j) {return i / j; } }
    51. };
    52. for (auto& str : tokens)
    53. {
    54. if (opFuncMap.find(str) != opFuncMap.end())
    55. {
    56. int right = st.top();
    57. st.pop();
    58. int left = st.top();
    59. st.pop();
    60. st.push(opFuncMap[str](left, right));
    61. }
    62. else
    63. {
    64. // 1、atoi itoa
    65. // 2、sprintf scanf
    66. // 3、stoi to_string C++11
    67. st.push(stoi(str));
    68. }
    69. }
    70. return st.top();
    71. }
    72. };

    2.3 bind

    std::bind函数定义在头文件中,是一个函数模板,它就像一个函数包装器(适配器)接受一个可 调用对象(callable object),生成一个新的可调用对象来“适应”原对象的参数列表。一般而言,我们用它可以把一个原本接收N个参数的函数fn,通过绑定一些参数,返回一个接收M个(M可以大于N,但这么做没什么意义)参数的新函数。同时,使用std::bind函数还可以实现参数顺 序调整等操作。
    1. // 原型如下:
    2. template <class Fn, class... Args>
    3. /* unspecified */ bind (Fn&& fn, Args&&... args);
    4. // with return type (2)
    5. template <class Ret, class Fn, class... Args>
    6. /* unspecified */ bind (Fn&& fn, Args&&... args);
    可以将bind函数看作是一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。
    调用bind的一般形式:auto newCallable = bind(callable,arg_list);
    其中,newCallable本身是一个可调用对象,arg_list是一个逗号分隔的参数列表,对应给定的callable的参数。当我们调用newCallable时,newCallable会调用callable,并传给它arg_list中 的参数
    arg_list中的参数可能包含形如_n的名字,其中n是一个整数,这些参数是“占位符”,表示
    newCallable的参数,它们占据了传递给newCallable的参数的“位置”。数值n表示生成的可调用对 象中参数的位置:_1为newCallable的第一个参数,_2为第二个参数,以此类推。
    1. // 使用举例
    2. #include
    3. int Plus(int a, int b)
    4. {
    5. return a + b;
    6. }
    7. class Sub
    8. {
    9. public:
    10. int sub(int a, int b)
    11. {
    12. return a - b;
    13. }
    14. };
    15. int main()
    16. {
    17. //表示绑定函数plus 参数分别由调用 func1 的第一,二个参数指定
    18. std::function<int(int, int)> func1 = std::bind(Plus, placeholders::_1,
    19. placeholders::_2);
    20. //auto func1 = std::bind(Plus, placeholders::_1, placeholders::_2);
    21. //func2的类型为 function 与func1类型一样
    22. //表示绑定函数 plus 的第一,二为: 1, 2
    23. auto  func2 = std::bind(Plus, 1, 2);
    24. cout << func1(1, 2) << endl;
    25. cout << func2() << endl;
    26. Sub s;
    27. // 绑定成员函数
    28. std::function<int(int, int)> func3 = std::bind(&Sub::sub, s,
    29. placeholders::_1, placeholders::_2);
    30. // 参数调换顺序
    31. std::function<int(int, int)> func4 = std::bind(&Sub::sub, s,
    32. placeholders::_2, placeholders::_1);
    33. cout << func3(1, 2) << endl;
    34. cout << func4(1, 2) << endl;
    35. return 0;
    36. }

    举例:

     

    1. #include
    2. int f(int a, int b)
    3. {
    4. return a + b;
    5. }
    6. struct Functor
    7. {
    8. public:
    9. int operator() (int a, int b)
    10. {
    11. return a + b;
    12. }
    13. };
    14. class Plus
    15. {
    16. public:
    17. Plus(int x=2)
    18. :_x(x)
    19. {}
    20. int plusi(int a, int b)
    21. {
    22. return (a + b)*2;
    23. }
    24. private:
    25. int _x;
    26. };
    27. int main()
    28. {
    29. // 函数名(函数指针)
    30. std::function<int(int, int)> func1 = f;
    31. cout << func1(1, 2) << endl;
    32. // 函数对象
    33. std::function<int(int, int)> func2 = Functor();
    34. cout << func2(10, 20) << endl;
    35. std::function<int(Plus, int, int)> func5 = &Plus::plusi;
    36. cout << func5(Plus(), 100, 200) << endl;
    37. return 0;
    38. }

     

     

     

     

    1. int f(int a, int b)
    2. {
    3. return a + b;
    4. }
    5. struct Functor
    6. {
    7. public:
    8. int operator() (int a, int b)
    9. {
    10. return a + b;
    11. }
    12. };
    13. class Plus
    14. {
    15. public:
    16. Plus(int x=2)
    17. :_x(x)
    18. {}
    19. int plusi(int a, int b)
    20. {
    21. return (a + b)*_x;
    22. }
    23. private:
    24. int _x;
    25. };
    26. int main()
    27. {
    28. // 函数名(函数指针)
    29. std::function<int(int, int)> func1 = f;
    30. cout << func1(1, 2) << endl;
    31. // 函数对象
    32. std::function<int(int, int)> func2 = Functor();
    33. cout << func2(10, 20) << endl;
    34. //1.直接包装的是3个参数
    35. std::function<int(Plus, int, int)> func3 = &Plus::plusi;
    36. cout << func3(Plus(), 100, 200) << endl;
    37. //2.1 bind绑定,调整了个数,为2个参数
    38. std::function<int(int, int)> func4 = std::bind(&Plus::plusi,Plus(10),
    39. placeholders::_1,placeholders::_2);
    40. //第一个对象Plus(10)已经绑死,后面两个对象占位placeholders::_1,placeholders::_2是显式传参,占位
    41. cout << func4(100, 200) << endl;
    42. //2.2 bind绑定,调整了个数,为1个参数
    43. std::function<int(int)> func5 = std::bind(&Plus::plusi, Plus(10),15, placeholders::_1);
    44. //第一个Plus(10)、第二个对象15已经绑死,后面一个对象占位placeholders::_1是显式传参,占位
    45. cout << func5( 200) << endl;
    46. return 0;
    47. }

     第一个func3是显式传参,显式用的是匿名对象Plus(),没有传参数就用缺省参数2
    第二个func4没有传Plus对象,因为bind绑定相当于包了一层传给function,可以认为把参数给调整了。第一个参数Plus(10)已经传了,相当于写死了。传的就是10,其实内部还是用Plus去调用!
    绑定可以调整可调用对象的参数个数和顺序!
    Func3直接包装是3个参数!
    Func4bind绑定调整为2个参数!
    _1、_2、_3表示要自己传的参数

     

     

     

     

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. using namespace std;
    7. int f(int a, int b)
    8. {
    9. return a - b;
    10. }
    11. struct Functor
    12. {
    13. public:
    14. int operator() (int a, int b)
    15. {
    16. return a + b;
    17. }
    18. };
    19. class Plus
    20. {
    21. public:
    22. Plus(int x=2)
    23. :_x(x)
    24. {}
    25. int plusi(int a, int b)
    26. {
    27. return (a + b)*_x;
    28. }
    29. private:
    30. int _x;
    31. };
    32. int f(int a, int b)
    33. {
    34. return a - b;
    35. }
    36. int main()
    37. {
    38. // 函数名(函数指针)
    39. std::function<int(int, int)> func1 = f;
    40. cout << "func1(1, 2):\t\t" << func1(1, 2) << endl;
    41. //bind调整顺序
    42. std::function<int(int, int)> func6 = std::bind(f, placeholders::_2, placeholders::_1);
    43. cout << "func6(1, 2):\t\t" << func6(1, 2) << endl;
    44. // 函数对象
    45. std::function<int(int, int)> func2 = Functor();
    46. cout << "func2(10, 20):\t\t" << func2(10, 20) << endl;
    47. //1.直接包装的是3个参数
    48. std::function<int(Plus, int, int)> func3 = &Plus::plusi;
    49. cout << "func3(Plus(), 100, 200):" << func3(Plus(), 100, 200) << endl;
    50. //2.1 bind绑定,调整了个数,为2个参数
    51. std::function<int(int, int)> func4 = std::bind(&Plus::plusi,Plus(10),
    52. placeholders::_1,placeholders::_2);
    53. //第一个对象Plus(10)已经绑死,后面两个对象占位placeholders::_1,placeholders::_2是显式传参,占位
    54. cout << "func4(100, 200):\t" << func4(100, 200) << endl;
    55. //2.2 bind绑定,调整了个数,为1个参数
    56. std::function<int(int)> func5 = std::bind(&Plus::plusi, Plus(10),15, placeholders::_1);
    57. //第一个Plus(10)、第二个对象15已经绑死,后面一个对象占位placeholders::_1是显式传参,占位
    58. cout << "func5(200):\t" << func5(200) << endl;
    59. mapint(int, int)>> opFuncMap =
    60. {
    61. {"普通函数指针",f},
    62. {"函数对象",Functor()},
    63. {"成员函数指针",std::bind(&Plus::plusi,Plus(10),
    64. placeholders::_1,placeholders::_2)}
    65. };
    66. cout << "普通函数指针(1, 2):\t" << opFuncMap["普通函数指针"](1, 2) << endl;
    67. cout << "函数对象(1, 2):\t" << opFuncMap["函数对象"](1, 2) << endl;
    68. cout << "成员函数指针(1, 2):\t" << opFuncMap["成员函数指针"](1, 2) << endl;
    69. return 0;
    70. }

     总结:bind绑定可以调整参数个数和参数传参顺序!

    后记:
    ●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!

                                                                               ——By 作者:新晓·故知

     

  • 相关阅读:
    Python、C、C扩展、Cython 差异对比,98%的人都不知道
    【深基13.例1】查找
    亚马逊要求纽扣电池出口IEC60086测试报告申请流程
    解决svn update 产生Node remains in conflict的报错问题
    JDK版本对应其major.minor version,看这一篇就够啦(附java历史版本下载地址)
    lnmp架构之mysql部署
    阿里是如何使用分布式架构的?阿里内部学习手册分享
    Java内部类分类
    Java字符串String、StringBuffer、StringBuilder的异同
    InputMan12.0J
  • 原文地址:https://blog.csdn.net/m0_57859086/article/details/127036453