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;
return ddd;
});
看个简单的例子:
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
=>
它等价于
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);
原文链接: https://www.cnblogs.com/davidgu/p/4825625.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/222090
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!