Lambda Expressions in C++ – Syntax, Examples and Advantages

A Lambda Expression in C++ is an anonymous function (a function without a name) that can be defined directly where it is needed. Lambda expressions are useful for writing short functions, passing functionality to other functions, and performing operations on collections of data. Lambda expressions were introduced in C++11 and are widely used with Standard Library algorithms such as sort(), for_each(), find_if(), and count_if().

C++ में Lambda Expression एक Anonymous Function (बिना नाम वाला Function) होता है, जिसे आवश्यकता के अनुसार सीधे Program में Define किया जा सकता है। Lambda Expressions का उपयोग छोटे Functions लिखने, दूसरे Functions को Functionality Pass करने और Data Collections पर Operations करने के लिए किया जाता है। Lambda Expressions को C++11 में Introduce किया गया था। इनका उपयोग Standard Library Algorithms जैसे sort(), for_each(), find_if() और count_if() के साथ व्यापक रूप से किया जाता है।

Syntax of Lambda Expression – Lambda Expression का सिंटैक्स

[capture_clause](parameters) -> return_type
{
// Statements
};

Components of Lambda Expression – Lambda Expression के भाग

  1. Capture Clause [ ]: Specifies which variables from the surrounding scope are accessible inside the lambda.

    Capture Clause [ ]: यह निर्धारित करता है कि Surrounding Scope के कौन-से Variables Lambda के अंदर उपयोग किए जा सकते हैं।

  2. Parameter List ( ): Specifies the input parameters accepted by the lambda. It is optional when no parameters are required.

    Parameter List ( ): इसमें Lambda द्वारा स्वीकार किए जाने वाले Input Parameters लिखे जाते हैं। Parameters की आवश्यकता न होने पर इसे खाली रखा जा सकता है।

  3. Return Type ->: Specifies the return type of the lambda. It is generally optional because the compiler can usually deduce the return type.

    Return Type ->: यह Lambda का Return Type निर्धारित करता है। सामान्यतः इसे लिखना आवश्यक नहीं होता क्योंकि Compiler Return Type का अनुमान लगा सकता है।

  4. Function Body { }: Contains the statements executed when the lambda is called.

    Function Body { }: इसमें वे Statements लिखे जाते हैं जो Lambda Call होने पर Execute होते हैं।

Example 1: Simple Lambda Expression in C++

The following program demonstrates a simple lambda expression that displays a message.

निम्न प्रोग्राम में एक Simple Lambda Expression की सहायता से Message Display किया गया है।

Source Code:

#include <iostream>
using namespace std;
int main()
{
auto message = []()
{
cout << "Welcome to C++ Lambda Expressions!";
};
message();
return 0;
}

Output:

Welcome to C++ Lambda Expressions!

Explanation – व्याख्या:

  • [] represents the capture clause. It is empty because no outside variables are used.

  • () indicates that the lambda takes no parameters.

  • auto allows the compiler to determine the lambda's type.

  • message() calls the lambda expression.

  • [] Capture Clause को दर्शाता है। यह खाली है क्योंकि किसी बाहरी Variable का उपयोग नहीं किया गया है।

  • () बताता है कि Lambda कोई Parameter स्वीकार नहीं करता।

  • auto Compiler को Lambda का Type निर्धारित करने देता है।

  • message() Lambda Expression को Call करता है।

Example 2: Lambda Expression with Parameters

A lambda expression can accept parameters just like a normal function. In this example, the lambda receives two numbers and returns their sum.

Lambda Expression सामान्य Function की तरह Parameters स्वीकार कर सकता है। इस उदाहरण में Lambda दो Numbers प्राप्त करके उनका Sum Return करता है।

Source Code:

#include <iostream>
using namespace std;
int main()
{
auto addition = [](int a, int b)
{
return a + b;
};
cout << "Sum = " << addition(10, 20);
return 0;
}

Output:

Sum = 30

Explanation – व्याख्या:

The lambda addition accepts two integer parameters, a and b. It returns their sum. The expression addition(10, 20) calls the lambda with two arguments.

Lambda addition दो Integer Parameters a और b स्वीकार करता है और उनका Sum Return करता है। Expression addition(10, 20) दो Arguments के साथ Lambda को Call करता है।

Example 3: Lambda Expression with Return Type

The return type of a lambda can be specified explicitly using the arrow operator ->.

Lambda का Return Type Arrow Operator -> की सहायता से स्पष्ट रूप से निर्धारित किया जा सकता है।

Source Code:

#include <iostream>
using namespace std;
int main()
{
auto maximum = [](int a, int b) -> int
{
if (a > b)
return a;
return b;
};
cout << "Maximum = " << maximum(15, 25);
return 0;
}

Output:

Maximum = 25

Here, -> int explicitly specifies that the lambda returns an integer value.

यहाँ -> int स्पष्ट करता है कि Lambda एक Integer Value Return करता है।

Capture Clause in Lambda Expressions – Lambda में Capture Clause

The capture clause is one of the most important features of lambda expressions. It allows a lambda to access variables declared outside its body.

Capture Clause Lambda Expression की सबसे महत्वपूर्ण विशेषताओं में से एक है। इसकी सहायता से Lambda अपने Body के बाहर Declare किए गए Variables को Access कर सकता है।

Common capture methods are:

1. Empty Capture [ ]

An empty capture clause means that the lambda does not capture any outside local variables.

Empty Capture Clause का अर्थ है कि Lambda किसी भी बाहरी Local Variable को Capture नहीं करता।

auto display = []()
{
cout << "Hello C++";
};

2. Capture by Value [=]

Capture by value makes copies of the used local variables from the surrounding scope. Changes to the captured copies do not change the original variables.

Capture by Value में Surrounding Scope के उपयोग किए गए Local Variables की Copies बनाई जाती हैं। Captured Copies में बदलाव करने से Original Variables नहीं बदलते।

Example:

#include <iostream>
using namespace std;
int main()
{
int x = 10;
auto show = [=]()
{
cout << "Value of x = " << x;
};
show();
return 0;
}

Output:

Value of x = 10

3. Capture by Reference [&]

Capture by reference allows the lambda to access the original local variables through references. Changes made inside the lambda can affect the original variables.

Capture by Reference Lambda को References के माध्यम से Original Local Variables Access करने देता है। Lambda के अंदर किए गए बदलाव Original Variables को प्रभावित कर सकते हैं।

Example:

#include <iostream>
using namespace std;
int main()
{
int x = 10;
auto change = [&]()
{
x = 50;
};
change();
cout << "Value of x = " << x;
return 0;
}

Output:

Value of x = 50

4. Capturing a Specific Variable [x] or [&x]

A lambda can capture a specific variable by value or by reference instead of capturing all used local variables.

Lambda सभी उपयोग किए गए Local Variables को Capture करने के बजाय किसी विशेष Variable को Value या Reference के रूप में Capture कर सकता है।

int x = 10;
auto a = [x]() { return x; }; // Capture by value
auto b = [&x]() { return x; }; // Capture by reference

Example 4: Using Lambda Expression with for_each()

The for_each() algorithm applies a given operation to every element in a range. A lambda expression can be passed directly to it.

for_each() Algorithm किसी Range के प्रत्येक Element पर दिए गए Operation को Apply करता है। इसमें Lambda Expression को सीधे Pass किया जा सकता है।

Source Code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers = {10, 20, 30, 40, 50};
for_each(numbers.begin(), numbers.end(),
[](int n)
{
cout << n << " ";
});
return 0;
}

Output:

10 20 30 40 50

Explanation – व्याख्या:

  • A vector named numbers stores five integer values.

  • for_each() visits every element in the vector.

  • The lambda receives each element as n and displays it.

  • numbers नाम का Vector पाँच Integer Values Store करता है।

  • for_each() Vector के प्रत्येक Element पर कार्य करता है।

  • Lambda प्रत्येक Element को n के रूप में प्राप्त करके Display करता है।

Example 5: Sorting Using Lambda Expression

Lambda expressions can be used with the sort() algorithm to customize the sorting order. The following example sorts numbers in descending order.

Lambda Expressions का उपयोग sort() Algorithm के साथ Sorting Order निर्धारित करने के लिए किया जा सकता है। निम्न उदाहरण में Numbers को Descending Order में Sort किया गया है।

Source Code:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers = {40, 10, 50, 20, 30};
sort(numbers.begin(), numbers.end(),
[](int a, int b)
{
return a > b;
});
for (int n : numbers)
{
cout << n << " ";
}
return 0;
}

Output:

50 40 30 20 10

Explanation – व्याख्या:

The lambda [](int a, int b) { return a > b; } compares two elements. It returns true when a should appear before b, resulting in descending order.

Lambda [](int a, int b) { return a > b; } दो Elements की तुलना करता है। जब a, b से पहले आना चाहिए, तब यह true Return करता है। इस प्रकार Numbers Descending Order में Sort होते हैं।

Advantages of Lambda Expressions – Lambda Expressions के लाभ

  1. Shorter Code: Lambda expressions allow small functions to be written directly where they are needed.

    कम Code: Lambda Expressions छोटे Functions को आवश्यकता के स्थान पर सीधे लिखने की सुविधा देते हैं।

  2. No Separate Function Required: There is no need to define a separate named function for simple operations.

    अलग Function की आवश्यकता नहीं: छोटे Operations के लिए अलग Named Function बनाने की आवश्यकता नहीं होती।

  3. Useful with STL Algorithms: Lambdas work conveniently with algorithms such as sort(), for_each(), and find_if().

    STL Algorithms में उपयोगी: Lambda का उपयोग sort(), for_each() और find_if() जैसे Algorithms के साथ आसानी से किया जा सकता है।

  4. Variable Capture: Lambdas can access variables from their surrounding scope by value or reference.

    Variable Capture: Lambda अपने आसपास के Scope के Variables को Value या Reference के रूप में Access कर सकता है।

  5. Improved Readability: Small operations can be written close to the code where they are used, making the program easier to follow.

    बेहतर Readability: छोटे Operations को उसी स्थान पर लिखा जा सकता है जहाँ उनका उपयोग होता है, जिससे Program को समझना आसान होता है।

Lambda expressions are a useful feature of modern C++ that allow programmers to create short anonymous functions. They are especially helpful with STL algorithms, sorting, filtering, and operations on collections. Their capture clause also provides a convenient way to access variables from the surrounding scope.

Lambda Expressions Modern C++ की एक उपयोगी विशेषता हैं, जिनकी सहायता से छोटे Anonymous Functions बनाए जा सकते हैं। ये विशेष रूप से STL Algorithms, Sorting, Filtering और Collections पर Operations करने में उपयोगी हैं। इनका Capture Clause Surrounding Scope के Variables को Access करने की सुविधा भी प्रदान करता है।

Comments

Popular posts from this blog

Important Questions (IMP) of Programming Methodologies and Data structures using C++ with OOP's Concepts

C++ Programming Syllabus Complete - From Basics to Advanced C++, including OOP and Data Structures and Algorithms (DSA)

OOP's using CPP Syllabus AND Programming Methodologies and Data Structures Using C++ (NEP 2020)