Lambda表达式语法定义
Lambda 表达式的基本语法如下:
[capture-list] (parameters) -> return-type {
// 函数体
}
例子:
int x = 10;
auto function = [=](int a, int b) mutable -> int {
return a + b + x;
}
int ret = function(10, 20); // 输出50
Lambda表达式参数详解
- []表示不捕获任何变量
- [var]表示值传递方式捕获变量var
- [=]表示值传递方式捕获所有父作用域的变量(包括this)
- [&var]表示引用传递捕捉变量var
- [&]表示引用传递方式捕捉所有父作用域的变量(包括this)
- [this]表示值传递方式捕捉当前的this指针
- [=, &] 拷贝与引用混合
Lamdba在STL中的应用
#include <algorithm>
#include <cmath>
void abssort(float* x, unsigned n) {
std::sort(x, x + n,
[](float a, float b) {
return (std::abs(a) < std::abs(b));
}
);
}
Lamdba表达式在QT中的应用
QTimer *timer=new QTimer;
timer->start(1000);
QObject::connect(timer, &QTimer::timeout, [&]() {
qDebug() << "time out";
});
int a = 10;
QString str1 = "Key press";
connect(pBtn4, &QPushButton::clicked, [=](bool checked) {
qDebug() << a <<str1;
qDebug() << checked;
});