How do define anonymous functions in C++?

Solution 1:

C++11 added lambda functions to the language. The previous versions of the language (C++98 and C++03), as well as all current versions of the C language (C89, C99, and C11) do not support this feature. The syntax looks like:

[capture](parameters)->return-type{body}

For example, to compute the sum of all of the elements in a vector:

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;
});

Solution 2:

In C++11, you can use closures:

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

   auto n = f(1, 2);
}

Prior to that, you can use local classes:

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

   int n = f(1, 2);
}

Both versions can be made to refer to ambient variables: In the local class, you can add a reference member and bind it in the constructor; and for the closure you can add a capture list to the lambda expression.

Solution 3:

i dont know if i understand you well, but you want a lambda function?

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'; 
    }

if you dont have c++11x then try:

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