Home > Backend Development > C++ > body text

Do C++ lambda expressions support recursion?

WBOY
Release: 2024-04-17 21:06:01
Original
618 people have browsed it

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.

C++ lambda 表达式是否支持递归?

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;
}
Copy after login

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:

  • Ensure recursive conditions are clearly defined to prevent infinite recursion.
  • Deep recursion should be used with caution due to potential stack overflow.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template