C++
Beginner
1 min read
Lambdas, std::function, and Closures
Example
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <string>
int main() {
// Basic lambda
auto greet = [](const std::string& name) {
std::cout << "Hello, " << name << "!\n";
};
greet("Lambda");
// Capture by value
int threshold = 5;
auto isAbove = [threshold](int n) { return n > threshold; };
std::cout << "6 above threshold: " << std::boolalpha << isAbove(6) << "\n";
// Capture by reference — modifies outer variable
int count = 0;
auto increment = [&count]() { ++count; };
increment(); increment(); increment();
std::cout << "count = " << count << "\n"; // 3
// Lambda in STL algorithm
std::vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6};
std::sort(nums.begin(), nums.end(),
[](int a, int b) { return a > b; }); // descending
for (int n : nums) std::cout << n << " ";
std::cout << "\n";
// std::function — type-erased callable
std::vector<std::function<int(int)>> transforms;
transforms.push_back([](int n) { return n * 2; });
transforms.push_back([](int n) { return n + 10; });
transforms.push_back([](int n) { return n * n; });
int val = 3;
for (const auto& f : transforms)
std::cout << "f(" << val << ") = " << f(val) << "\n";
return 0;
}