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);
  • 相关阅读:
    WebSocket理解与使用
    JS面向对象与prototype,__proto__,constructor
    JS值传递与引用传递
    vue报错:./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!
    对于图片视频编辑类产品的思考
    时尚衣裙外贸独立站搭建(一)
    2021年Wordpress手把手教你做个独立站——部署篇
    一次备案失败所引发的思考
    2021年Wordpress博客装修美化(二)
    做什么,怎么做?(20210615)
  • 原文地址:https://www.cnblogs.com/davidgu/p/4825625.html
Copyright © 2011-2022 走看看