![]() |
In C++, lambda expressions provide a convenient way to create one-liner functions. One of the key features of lambdas is their ability to capture variables from their surrounding scope by using capture clauses. This allows lambdas to access and modify variables from the outer scope, even after the lambda itself has been created. In this article, we will learn about what are lambdas with capture clauses in C++. C++ Lambdas with Capture ClausesCapture clauses are specified within the square brackets after the lambda expression’s parameter list. They also define how the variables from the surrounding scope are being captured by the lambda. Following is the syntax for lambda expressions with capture clauses: Syntax[capture-list] (parameters) -> return-type { There are mainly two types of capture clauses in lambda expressions :
C++ Program to Capture a Variable by Value using LamdaIn the following example , we will capture a variable x by value in the lambda expression. Later the value of the variable is modified but it is not reflected inside the lambda function because the variable was captured using the value.
Output Inside lambda: 50 Outside lambda: 100 Time Complexity: O(1) C++ Program to Capture a Variable by Reference using LambdaIn the following example , we will capture a variable x by reference in the lambda expression. Later the value of the variable is modified and the modified value will be used in the lambda function as the variable was passed by reference.
Output Inside lambda: 100 Outside lambda: 100 |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |