如何在C++中定义匿名函数?

dan*_*jar 42 c++ syntax inline function

我可以用C++内联定义函数吗?我不是在讨论lambda函数,而不是inline导致编译器优化的关键字.

Ada*_*eld 58

C++ 11 在语言中添加了lambda函数.以前版本的语言(C++ 98和C++ 03)以及所有当前版本的C语言(C89,C99和C11)都不支持此功能.语法如下:

[capture](parameters)->return-type{body}
Run Code Online (Sandbox Code Playgroud)

例如,要计算向量中所有元素的总和:

std::vector<int> some_list;
int total = 0;
for (int i=0;i<5;i++) some_list.push_back(i);
std::for_each(begin(some_list), end(some_list), [&total](int x) {
  total += x;
});
Run Code Online (Sandbox Code Playgroud)

  • `int total = std :: accumulate(begin(some_list),end(some_list),0);`:) (7认同)

Ker*_* SB 25

在C++ 11中,您可以使用闭包:

void foo()
{
   auto f = [](int a, int b) -> int { return a + b; };

   auto n = f(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

在此之前,您可以使用本地类:

void bar()
{
   struct LocalClass
   {
       int operator()(int a, int b) const { return a + b; }
   } f;

   int n = f(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

可以使两个版本都引用环境变量:在本地类中,您可以添加引用成员并将其绑定在构造函数中; 对于闭包,您可以将捕获列表添加到lambda表达式.

  • 你的例子都没有形成闭包.第一个例子确实形成了一个匿名函数. (2认同)

Cyb*_*Guy 9

我不知道我是否理解你,但你想要一个lambda功能?

http://en.cppreference.com/w/cpp/language/lambda

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


    int main()
    {
        std::vector<int> c { 1,2,3,4,5,6,7 };
        int x = 5;
        c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; } ), c.end());

        std::cout << "c: ";
        for (auto i: c) {
            std::cout << i << ' ';
        }
        std::cout << '\n';

        std::function<int (int)> func = [](int i) { return i+4; };
        std::cout << "func: " << func(6) << '\n'; 
    }
Run Code Online (Sandbox Code Playgroud)

如果你没有c ++ 11x,那么试试:

http://www.boost.org/doc/libs/1_51_0/doc/html/lambda.html


Tho*_*ing 5

Pre C++ 11,如果要将函数本地化为函数,可以这样做:

int foo () {
    struct Local {
        static int bar () {
            return 1;
        }
    };
    return Local::bar();
}
Run Code Online (Sandbox Code Playgroud)

或者如果你想要更复杂的东西:

int foo (int x) {
    struct Local {
        int & x;
        Local (int & x) : x(x) {}
        int bar (int y) {
            return x * x + y;
        }
    };
    return Local(x).bar(44);
}
Run Code Online (Sandbox Code Playgroud)

但是如果你想在C++ 11之前使用真正的函数文字,那是不可能的.