zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    mysql 远程连接数据库的二种方法
    安装mysql-5.7.12-winx64
    快速提升word文档编写质量
    查看linux系统版本命令汇总
    SpringMVC+mybatis+maven+Ehcache缓存实现
    linux下的java开发环境
    appium 常用api介绍(2)
    appium 常用api介绍(1)
    appium入门
    Mysql5.7服务下载安装
  • 原文地址:https://www.cnblogs.com/davidgu/p/4825625.html
Copyright © 2011-2022 走看看