How to Define Lambda Functions in C++11?


C++11 (formerly named C++0x) has some great new features to improve the code efficiency such as the use of auto which is the same as the var in C#, the programmers do no need to explicity define the type of variables but the compiler will figure out the best-match variable type.

Quick Introduction to C++ Lambda function

The Lambda function is a short function that can normally be declared in one line. It is supported in many other programming languages as well, such as R, Python, and C#. The lambda function can be usually used as a function pointer or delegate where it is very easy to pass a function as a function parameter or return a function as a type. Now, lets define the first lambda in C++11.

1
auto p = [](int x, int y) { return x + y; };
auto p = [](int x, int y) { return x + y; };

So, the variable p is the lambda function, and you can use it like a normal function.

1
cout << p(3, 4);
cout << p(3, 4);

The good thing about using lambda functions is that you can just define them inside the local function, so they are used locally and will be freed when they are out of scope. Limited scopes is one of the good programming practice and it is like try not to declare global variables. Lambda functions are normally declared inside functions so they won’t conflict with whatever defined outside current local functions.

C-11-CPP-11-features How to Define Lambda Functions in C++11? c / c++ recursive tutorial

C++-11-CPP-11-features

Using Lambda function as function delegate

You can also use the lambda functions like function delegates:

1
2
3
int test(int(*F)(int, int), int x, int y) {
    return F(x, y);
}
int test(int(*F)(int, int), int x, int y) {
	return F(x, y);
}

and pass the lambda function as a parameter:

1
cout << test(p, 3, 4);
cout << test(p, 3, 4);

Use Lambda to Define Recursions

A recursion is a function that calls itself, like this. The following straightforward lambda function to compute the Fibonacci numbers will NOT work:

1
auto fib = [&fib](int n) {return n < 2 ? 1 : fib(n - 1) + fib(n - 2); };
auto fib = [&fib](int n) {return n < 2 ? 1 : fib(n - 1) + fib(n - 2); };

This is because the C3536 ‘fib’: cannot be used before it is initialized. We can, however, fix this by introduction the std::function (that you need to include the functional header file).

1
std::function<int(int)> f = [&f](int n) {return n < 2 ? 1 : f(n - 1) + f(n - 2); };
std::function<int(int)> f = [&f](int n) {return n < 2 ? 1 : f(n - 1) + f(n - 2); };

We explicity specify the type of the lambda function and this is not just the C++11 syntax sugar and it is elegant and works like a charm!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
573 words
Last Post: C/C++ Coding Exercise - Ransom Note (unordered_map or array)
Next Post: How to Display Directories Only Under Linux Shells?

The Permanent URL is: How to Define Lambda Functions in C++11?

Leave a Reply