Lambda Expressions

Anonymous functions in C++11+

Interview Relevant: Modern C++ feature

Lambda Expressions

Lambdas are anonymous functions defined inline (C++11).

Syntax: [capture](params) -> return { body }

  • [=]: Capture all by value
  • [&]: Capture all by reference
  • [x, &y]: x by value, y by reference
  • [this]: Capture this pointer

Code Examples

Lambda expressions with various capture modes.

cpp
1// Basic lambda
2auto add = [](int a, int b) { return a + b; };
3cout << add(3, 4);  // 7
4
5// Lambda with capture
6int multiplier = 3;
7auto multiply = [multiplier](int x) { return x * multiplier; };
8cout << multiply(5);  // 15
9
10// Capture by reference
11int counter = 0;
12auto increment = [&counter]() { counter++; };
13increment();  // counter is now 1
14
15// Using with STL algorithms
16vector<int> nums = {3, 1, 4, 1, 5, 9};
17sort(nums.begin(), nums.end(), [](int a, int b) {
18    return a > b;  // Descending order
19});
20
21// Find with lambda
22auto it = find_if(nums.begin(), nums.end(),
23    [](int n) { return n > 4; });
24
25// Generic lambda (C++14)
26auto print = [](auto x) { cout << x << endl; };
27print(42);
28print("Hello");
29
30// Lambda with mutable (modify captured values)
31int x = 10;
32auto modify = [x]() mutable { x++; return x; };

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In