Home >Backend Development >C++ >Do C++ lambda expressions support recursion?
Yes, C Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a lambda expression can call itself recursively.
Recursion of lambda expressions in C
Lambda expressions are a powerful feature in C that allow you to run When defining an anonymous function object. Generally, lambda expressions cannot be recursive because they cannot capture their own references. However, there is a technique to support recursion of lambda expressions using std::function.
Using std::function
std::function is a function object that can hold a reference to any callable object, including lambda expressions. By using std::function to capture a reference to a lambda expression, you can create a lambda expression that can be called recursively.
Code Example
The following code example shows how to use std::function to enable recursion of a lambda expression:
#include <functional> int fibonacci(int n) { std::function<int(int)> fib = [&fib](int n) { if (n <= 1) { return n; } return fib(n - 1) + fib(n - 2); }; return fib(n); } int main() { int result = fibonacci(5); std::cout << "Fibonacci of 5 is: " << result << "\n"; return 0; }
In this example, lambda The expression fib
captures a reference to itself fib
. This way it can call itself recursively to calculate Fibonacci numbers.
Note
Although std::function can be used to support recursion of lambda expressions, you still need to pay attention to the following when using recursion:
The above is the detailed content of Do C++ lambda expressions support recursion?. For more information, please follow other related articles on the PHP Chinese website!