• STL


    Lambda始自C++ 11,是一种在表达式或语句内指定函数行为的定义式。

    你可以定义函数行为作为对象,以inline实参的形式传给算法作为predicate(判断式)。

    eg:

    std:transform(coll.begin(), coll.end(),  // source

                         coll.begin(),                 // destination

                   

    #include <algorithm>
    #include <deque>
    #include <iostream>
    #include "LambdaTest.h"
    #include "../../Core/ContainerUtil.h"
    
    using namespace std;
    
    deque<int> coll = { 1, 3, 19, 5, 13, 7, 11, 2, 17 };
    
    cout << "all elements:" << endl;
    ContainerUtil<deque<int>>::printElements(coll);
    
    int x, y;
    cout << "Input x: ";
    cin >> x;
    cout << endl;
    cout << "Input y: ";
    cin >> y;
    cout << endl;
    auto pos = find_if(coll.cbegin(), coll.cend(),  // range
        [=](int i) {                 // search criterion
        return i > x && i < y;
    });
    
    cout << "first elem >"<< x <<" and <"<< y <<": " << *pos << endl;

          [](double d) {          // lambda as function object

                           return d*d*d;

                         });

    看个简单的例子:

    findFirstInRange.cpp

    运行结果:

    all elements:   1  3  19  5  13  7  11  2  17

    Input x: 5

    Input y: 18

    first elem >5 and <18: 13

    注意点:

    [=]

    这个符号表明在lambda被声明时已有效的所有符号都以传值(by value)的形式传入lambda体内

    [&]

    这个符号表明在lambda被声明时已有效的所有符号都以传引用(by reference)的形式传入lambda体内

    lambda内部可以改动他们的值

    上面例子lambda的等价物

    auto pos = find_if(coll.cbegin(), coll.cend(),  // range
        [=](int i) {                 // search criterion
        return i > x && i < y;
    });

    它等价于

    1. 手写的循环

    deque<int>::iterator pos;
    for (pos = coll.begin;pos!=coll.end(); ++pos)
    {
      if (*pos > x && *pos < y)
      {
         break;
      }
    }

    2. predicate(判断式)

    bool pred(int I)
    {
      return I > x && I < y;
    }
    
    ...
    
    pos = find_if(coll.begin(), coll.end(), pred);
  • 相关阅读:
    中移动ipv6-老毛子固件获取ipv6设置
    win7-win10 禁用IPV6临时地址
    辅助调用函数【call,apply,bind】
    Unraid修改docker镜像地址&默认启动
    docker基本入门知识-小白向
    [不止于代码]Unraid基本使用速记
    Dockerfile文件说明
    Git之pull,fetch差别
    代码片段添加智能提示,打造一款人见人爱的ORM框架
    新定义三层,指挥官模式
  • 原文地址:https://www.cnblogs.com/davidgu/p/4825625.html
Copyright © 2020-2023  润新知