lambda函数的用途是什么?

What is the use of lambda functions?

本文关键字:是什么 函数 lambda      更新时间:2023-10-16

谁能帮我理解下面的代码

#include <iostream>
using namespace std;
int main()
{
    auto hello = []() -> void {
        cout << "Hello World";
    };
    // Call the lambda function
    hello();
}

这里auto hello = []() -> void有什么用?我不明白花括号(第7行)后面的终止分号的含义

把它当作一行来读:

auto hello = []() -> void { cout << "Hello World"; };

hello是一个变量,它包含

  • 不捕获外部变量([]),
  • 不带参数(()),
  • 返回void (-> void,这被称为'尾随返回类型',指定lambda的返回类型,就像您对普通函数一样。),和
  • 由单个cout语句组成。

直到下一行显式调用它时才实际执行。