C++拉姆达表达式

发布于 2024-10-26 23:54:27 字数 65 浏览 1 评论 0 原文

我正在尝试理解 lambda 表达式。

它超出了我的想象。 请需要不言自明的例子

I am trying to understand lambda expression.

Its going over my head. Need self explanatory examples

Please !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

没︽人懂的悲伤 2024-11-02 23:54:27

如果您熟悉当前的 C++ 仿函数(即实现了operator() 的类,以便可以像函数一样调用它们,但具有可以初始化的内部数据成员),那么基本上就是 lambda是对该语言功能的一个很好的扩展,它使您能够创建函子并在调用它们时初始化它们,而不必定义函子类。 Lambda 也非常灵活,因为它们可以是闭包,允许您“捕获”当前范围内任何变量的值。

我觉得这是 Visual C++ 团队博客上非常好的资源,其中包含许多以下功能:
Lambda、auto 和 static_assert:VC10 中的 C++0x 功能,第 1 部分

希望这会有所帮助,

Jason

If you are familiar with the current C++ functors (i.e., classes that implement operator() so that they can be called like a function, but have internal data-members that can be initialized), then basically lambdas are a nice extension to that language feature by enabling you to create functors as well as initialize them at the point where they are going to be called rather than having to define functor classes. Lambdas are also quite flexible as they can be closures, allowing you to "capture" the values of any variables in the current scope.

I felt this was a really great resource on the Visual C++ Team Blog that went through a lot of these features:
Lambdas, auto, and static_assert: C++0x Features in VC10, Part 1

Hope this helps,

Jason

香橙ぽ 2024-11-02 23:54:27

lambda 表达式是一种指定函数对象的机制。 lambda 的主要用途是指定某个函数要执行的简单操作。例如:

vector<int> v = {50, -10, 20, -30};

std::sort(v.begin(), v.end());  // the default sort
// now v should be { -30, -10, 20, 50 }

// sort by absolute value:
std::sort(v.begin(), v.end(), [](int a, int b) { return abs(a)<abs(b); });
// now v should be { -10, 20, -30, 50 }

参数 [&](int a, int b) { return abs(a) 是一个“lambda”(或“lambda 函数”或“lambda 表达式”),它指定给定两个整数参数 a 和 b 的操作,返回比较它们的绝对值的结果。

[&] 是一个“捕获列表”,指定所使用的本地名称将通过引用传递。我们可以说我们只想“捕获”v,我们可以这样说:[&v]。如果我们想按值传递 v,我们可以这样说:[=v]。不捕获任何内容是 [],按引用捕获所有内容是 [&],按值捕获所有内容是 [=]。

http://www2.research.att.com/~bs/ C++0xFAQ.html#lambda

A lambda expression is a mechanism for specifying a function object. The primary use for a lambda is to specify a simple action to be performed by some function. For example:

vector<int> v = {50, -10, 20, -30};

std::sort(v.begin(), v.end());  // the default sort
// now v should be { -30, -10, 20, 50 }

// sort by absolute value:
std::sort(v.begin(), v.end(), [](int a, int b) { return abs(a)<abs(b); });
// now v should be { -10, 20, -30, 50 }

The argument [&](int a, int b) { return abs(a)<abs(b); } is a "lambda" (or "lambda function" or "lambda expression"), which specifies an operation that given two integer arguments a and b returns the result of comparing their absolute values.

The [&] is a "capture list" specifying that local names used will be passed by reference. We could have said that we wanted to "capture" only v, we could have said so: [&v]. Had we wanted to pass v by value, we could have said so: [=v]. Capture nothing is [], capture all by references is [&], and capture all by value is [=].

http://www2.research.att.com/~bs/C++0xFAQ.html#lambda

聚集的泪 2024-11-02 23:54:27

lambda 表达式(也称为 lambda 函数)是在调用位置定义的无名函数。

有关示例,请访问Lambda 表达式示例

更好的学习地点:

A lambda expression (also known as a lambda function) is nameless function defined at the place of call.

For examples, visit Examples on Lambda Expression

Better places to learn :

站稳脚跟 2024-11-02 23:54:27

如果您愿意的话,还有另一个例子:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    // Initialization C++0x-style
    vector<int> voo = { 1, 2, 3, 4, 5 };

    // Lambda is here
    auto print = [&](int& i) { cout << i << endl; } ;

    // Check that out, no loop !
    for_each(voo.begin(), voo.end(), print);

    return 0;
}

Also another example if you'd like :

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    // Initialization C++0x-style
    vector<int> voo = { 1, 2, 3, 4, 5 };

    // Lambda is here
    auto print = [&](int& i) { cout << i << endl; } ;

    // Check that out, no loop !
    for_each(voo.begin(), voo.end(), print);

    return 0;
}
书间行客 2024-11-02 23:54:27

拉姆达很简单。记住通用语法第一

[ capture list ] (parameters) -> return-type  
{   
    method definition
}

通常,Lambda 函数的返回类型由编译器本身计算,我们不需要显式指定,即 ->返回类型。

其余的是C++。

例如

  1. 捕获对象

    • [ ] ( ) { } 没有捕获
    • [=] ( ) { } 通过复制捕获所有内容(不推荐)
    • [&] ( ) { } 通过引用捕获所有内容(不推荐)
    • [x] ( ) { } 通过复制捕获 x
    • [&x] ( ) { } 通过引用捕获 x
    • [&, x] ( ) { } 通过复制捕获 x,通过引用捕获其他所有内容
      [=, &x] ( ) { } 通过引用捕获 x,通过复制捕获其他所有内容
  2. 捕获此指针

class Example
{
public:
    Example() : m_var(10) {}
    void func()
    {
        [=]() { std::cout << m_var << std::endl; }();
    }
private:
    int m_var;
};
int main()
{
    Example e;
    e.func();
}

this 指针也可以使用 [this]、[=] 或 [&] 捕获。在任何这些情况下,都可以像在普通方法中一样访问类数据成员(包括私有成员)。

  1. Lambda 作为参数
template <typename Functor>
void f(Functor functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}
/* Or alternatively you can use this
void f(std::function<int(int)> functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
} 
*/
int g() { static int i = 0; return i++; }
int main()
{
    auto lambda_func = [i = 0]() mutable { return i++; };
    f(lambda_func); // Pass lambda
    f(g);           // Pass function
}

输出:

Function Type : void f(Functor) [with Functor = main()::<lambda(int)>]
Function Type : void f(Functor) [with Functor = int (*)(int)]

来源:通过示例学习 C++ 中的 Lambda 函数

Lambda is simple. Remember generic syntax 1st

[ capture list ] (parameters) -> return-type  
{   
    method definition
}

Usually, return-type of a Lambda function is evaluated by the compiler itself and we don’t need to specify that explicitly i.e. -> return-type.

Rest is C++.

For example

  1. Capturing objects

    • [ ] ( ) { } no captures
    • [=] ( ) { } captures everything by copy(not recommendded)
    • [&] ( ) { } captures everything by reference(not recommendded)
    • [x] ( ) { } captures x by copy
    • [&x] ( ) { } captures x by reference
    • [&, x] ( ) { } captures x by copy, everything else by reference
      [=, &x] ( ) { } captures x by reference, everything else by copy
  2. Capturing this pointer

class Example
{
public:
    Example() : m_var(10) {}
    void func()
    {
        [=]() { std::cout << m_var << std::endl; }();
    }
private:
    int m_var;
};
int main()
{
    Example e;
    e.func();
}

this pointer can also be captured using [this], [=] or [&]. In any of these cases, class data members(including private) can be accessed as you do in normal method.

  1. Lambda as parameter
template <typename Functor>
void f(Functor functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}
/* Or alternatively you can use this
void f(std::function<int(int)> functor)
{
    std::cout << __PRETTY_FUNCTION__ << std::endl;
} 
*/
int g() { static int i = 0; return i++; }
int main()
{
    auto lambda_func = [i = 0]() mutable { return i++; };
    f(lambda_func); // Pass lambda
    f(g);           // Pass function
}

Output:

Function Type : void f(Functor) [with Functor = main()::<lambda(int)>]
Function Type : void f(Functor) [with Functor = int (*)(int)]

Source: Learn Lambda function in C++ with example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文