A Lambda Expression is an anonymous (unnamed) inline function object that can capture variables from its enclosing scope. Introduced in C++11, lambdas are indispensable when writing concise callbacks and algorithms.
[]: Empty capture clause (accesses only its arguments).[=]: Captures all local variables in scope by value (read-only copy).[&]: Captures all local variables in scope by reference (can modify originals).[this]: Captures the current class object instance pointer.[x, &y]: Captures variable x by value and variable y by reference.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 12, 18, 7, 25, 30};
int threshold = 15;
// Capture threshold by value, take element by const reference
int count = std::count_if(numbers.begin(), numbers.end(), [threshold](int n) {
return n > threshold;
});
std::cout << "Numbers greater than " << threshold << ": " << count << "\n"; // 3
// Generic auto lambda (C++14):
auto printer = [](const auto& item) {
std::cout << "[ITEM]: " << item << "\n";
};
printer(42);
printer("Modern C++");
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Passing inline lambdas to std::sort and std::count_if.
Compare named functions vs anonymous lambdas.
Spawning threads with inline lambda workers.