Lambda
Lambda Expression
- [capture clause](parameters) -> return-type {body}
Pass Parameters by Value
#include <iostream>
#include <vector>
#include <algorithm>
int main(int argc, char *argv[])
{
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto f = [](int x){if(x%2 == 0) std::cout<<x<<std::endl;};
for_each(v.begin(), v.end(), [](int x){if(x%2 == 0) std::cout<<x<<std::endl;});
for_each(v.begin(), v.end(), f);
return 0;
}
Pass Parameters by Reference
#include <iostream>
#include <vector>
#include <algorithm>
int main(int argc, char *argv[])
{
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for_each(v.begin(), v.end(), [](int &x){if(x%2 == 0) x *= 10;});
for_each(v.begin(), v.end(), [](int x) {std::cout<<x<<std::endl;});
return 0;
}
External Reference
#include <iostream>
#include <vector>
#include <algorithm>
int main(int argc, char *argv[])
{
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int num = 3;
//capture by value
std::cout<<"Capture by Value: "<<std::endl;
for_each(v.begin(), v.end(), [=](int &x){if(x%num == 0) std::cout<<num<<std::endl;});
//capture by reference
std::cout<<"Capture by Reference: "<<std::endl;
for_each(v.begin(), v.end(), [&](int &x){if(x%num == 0) {num++; std::cout<<num<<std::endl;}});
return 0;
}
- [=], capture all of the variables from the enclosing scope by value
- [&], capture all of the variables from the enclosing scope by reference
Lambda in Member Function of Class
//Rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
private:
double width;
double length;
public:
//constructor
Rectangle(double w, double l):width(w), length(l){}
//accessor
double getWidth() const {return width;}
double getLength() const {return length;}
double getArea() const {return width*length;}
void display()
{
auto f = [this](int i){if (i>10) std::cout<<getArea()<<std::endl;};
f(20);
}
};
#endif
External Capture by both Value and Reference
#include <iostream>
#include "Rectangle.h"
int main(int argc, char *argv[])
{
Rectangle r(5, 10);
double minWidth = 2;
double minLength =5;
auto f = [minWidth, &minLength](const Rectangle &r){std::cout<<minWidth<<std::endl; if(r.getLength() > minLength) minLength = r.getLength();};
f(r);
std::cout<<"Min Width: "<<minWidth<<std::endl;
std::cout<<"Min Length: "<<minLength<<std::endl;
return 0;
}
- [minWidth, &minLength], minWidth pass by value, minLength pass by reference
No External Reference
#include <iostream>
#include <vector>
#include <algorithm>
int main(int argc, char *argv[])
{
std::vector<int> v = {1, 2, 3, 4};
for_each(v.begin(), v.end(), [](int i){std::cout<<i<<std::endl;});
return 0;
}
Reference