Advanced9 min readLesson 43 of 50
What is a Lambda?
A lambda (C++11) is an anonymous, inline function — defined where you need it without naming it. Syntax:
[capture](parameters) -> returnType { body }
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Simple lambda
auto greet = [](string name) {
cout << "Hello, " << name << "!" << endl;
};
greet("Alice"); // Hello, Alice!
// Lambda with return type
auto add = [](int a, int b) -> int { return a + b; };
cout << add(3, 5) << endl; // 8
// Lambda with STL
vector<int> nums = {5, 2, 8, 1, 9, 3};
sort(nums.begin(), nums.end(), [](int a, int b) { return a > b; }); // descending
for (int n : nums) cout << n << " "; // 9 8 5 3 2 1
cout << endl;
return 0;
}
Capture Clauses
Lambdas can capture variables from the surrounding scope:
int threshold = 5;
// Capture by value [=]
auto isAbove = [=](int n) { return n > threshold; };
// Capture by reference [&]
int count = 0;
auto countAbove = [&count, threshold](int n) {
if (n > threshold) count++;
};
vector<int> data = {1, 7, 3, 9, 2, 6};
for (int n : data) countAbove(n);
cout << "Above " << threshold << ": " << count << endl; // 3
Lambdas with STL
vector<string> words = {"banana", "apple", "cherry", "date"};
// Sort by length
sort(words.begin(), words.end(),
[](const string& a, const string& b) { return a.size() < b.size(); });
// Filter with count_if
int shortWords = count_if(words.begin(), words.end(),
[](const string& s) { return s.size() <= 5; });
cout << "Short words: " << shortWords << endl;
Exercise
Given a vector of integers, use a lambda with remove_if and erase to remove all odd numbers. Print the result.
Show Solution
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
nums.erase(remove_if(nums.begin(), nums.end(),
[](int n) { return n % 2 != 0; }), nums.end());
for (int n : nums) cout << n << " "; // 2 4 6 8 10
cout << endl;
return 0;
}
Quiz
What does [&] in a lambda capture clause mean?
- A) Capture nothing
- B) Capture all variables by value
- C) Capture all variables by reference
- D) Capture only local variables
Answer
C) [&] captures all local variables by reference.
Summary
- Lambdas are anonymous inline functions:
[capture](params){ body }. - Capture by value with
[=], by reference with [&]. - Perfect with STL algorithms: sort, find_if, count_if, transform.