Lambda Expressions
Lambda expression (C++11+) ek anonymous (naam-less) function hai jo inline define kar sakte ho, usually ek doosre function ke argument ke roop mein (jaise sort() ko custom comparison dena). Syntax: [capture](parameters) { body }.
[] (capture clause) batata hai lambda apne surrounding scope ki variables kaise use karega — [x] value se capture karo (copy), [&x] reference se (original access), [=] sab kuch value se, [&] sab kuch reference se.
int main() {
// Basic lambda:
auto greet = []() { cout << "Hello!" << endl; };
greet(); // "Hello!"
// Parameters ke saath:
auto add = [](int a, int b) { return a + b; };
cout << add(3, 4) << endl; // 7
// Capture by value:
int threshold = 5;
auto isAboveThreshold = [threshold](int n) { return n > threshold; };
cout << isAboveThreshold(10) << endl; // 1 (true)
// Capture by reference — original modify bhi ho sakta hai:
int counter = 0;
auto increment = [&counter]() { counter++; };
increment(); increment();
cout << counter << endl; // 2
return 0;
}- [capture](params) { body } = inline anonymous function
- [x] = value capture, [&x] = reference capture
- STL algorithms (sort, find_if) ke saath bahut common
Lambda ka return type usually automatically infer ho jaata hai (body ke return statement se). Complex cases mein (jaise multiple return paths alag types ke), explicit return type -> Type se specify kar sakte ho.
auto divide = [](double a, double b) -> double {
if (b == 0) return 0.0;
return a / b;
};
cout << divide(10, 2) << endl; // 5
// Simple cases mein, -> Type zaroori nahi:
auto square = [](int x) { return x * x; }; // return type auto-inferred: intauto se lambda store karna sabse efficient hai (compiler exact type jaanta hai). Agar lambda ko kisi function parameter/return type ke roop mein pass karna ho (jaha exact type specify nahi kar sakte), std::function<ReturnType(Params)> use karte hain — thoda overhead hai, lekin flexible hai.
#include <functional>
auto lambda1 = [](int x) { return x * 2; }; // auto — fastest
function<int(int)> lambda2 = [](int x) { return x * 2; }; // std::function — flexible
void applyFunc(function<int(int)> f, int val) {
cout << f(val) << endl;
}
applyFunc(lambda1, 5); // 10