Lambdas
Overview
If you want to sort a Vector of Players by their score, std::sort requires you to write a custom 'Comparator' function. In older C++, you had to scroll to the top of your file, write a standalone function, and then pass it in. This scattered your logic and made code unreadable.
Modern C++ (C++11) introduced Lambda Expressions. A Lambda is an 'Anonymous Function'—a highly compressed function that you write inline, exactly at the exact line of code where it is needed. They are heavily utilized in multi-threading, STL algorithms, and event-handling (like UI button clicks).
Syntax
#include <iostream>
int main() {
// THE LAMBDA SYNTAX: [] (parameters) { body }
// 1. We store the anonymous function inside an 'auto' variable
auto sayHello = []() {
std::cout << "Hello from the Lambda!\n";
};
// 2. We execute it just like a normal function!
sayHello();
// 3. Lambda with parameters and a return value
auto add = [](int a, int b) {
return a + b;
};
std::cout << "Sum: " << add(5, 5) << "\n";
return 0;
}Common Pitfalls
- The Capture Clause Trap. Unlike normal functions, Lambdas are physically created inside other functions (like inside
main()). However, by default, a Lambda is mathematically BLIND to the variables around it. If you try to use a localmain()variable inside the lambda body, it will fail to compile. You must 'Capture' the variables using the[ ]brackets.
Interview Questions
[&] and [=] in a Lambda's Capture Clause?The Capture Clause dictates how the Lambda imports external variables. [&] imports every single local variable by Reference, allowing the Lambda to physically mutate the original variables. [=] imports every variable by Value (a read-only copy), physically blocking the Lambda from altering the external state.
Real-World Example
Using a Lambda directly inside std::count_if to count how many numbers are perfectly even, completely bypassing the need for a messy external function.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
// The Lambda is written instantly inline!
// It returns true if the number is even.
int evens = std::count_if(numbers.begin(), numbers.end(), [](int n) {
return (n % 2) == 0;
});
std::cout << "Even numbers found: " << evens << "\n"; // 3
return 0;
}Check Your Knowledge
Test your understanding of Lambdas with these quick questions.