Topic 79 of 83
Lambdas
Overview
Lambdas (C++11) are anonymous, inline functions. They are heavily used with STL algorithms (like `sort` or `count_if`) to provide custom logic on the fly without writing a whole new function.
Syntax
cpp
// Syntax: [captures] (parameters) -> return_type { body }
auto add = [](int a, int b) {
return a + b;
};
cout << add(5, 3); // 8
// Captures allow access to variables outside the lambda
int multiplier = 10;
auto scale = [multiplier](int val) {
return val * multiplier;
};Common Pitfalls
- Capturing a local variable by reference `[&]` in a lambda, and then returning that lambda from a function. The local variable dies, leaving the lambda with a dangling reference.
Interview Tips
- Understand the Capture Clause: `[=]` captures everything by value (read-only copy). `[&]` captures everything by reference (can modify original variables).
Real-World Example
Sorting a vector of objects using a lambda.
example
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Player { string name; int score; };
int main() {
vector<Player> players = {{"Alice", 50}, {"Bob", 90}, {"Charlie", 70}};
// Sort by score descending using a lambda
sort(players.begin(), players.end(), [](const Player& a, const Player& b) {
return a.score > b.score;
});
for (const auto& p : players) {
cout << p.name << ": " << p.score << endl;
}
return 0;
}