Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <iostream> #include <vector> #include <algorithm> #include <functional> #include <string> int main() { // Basic lambda auto greet = [](const std::string& name) { std::cout << "Hello, " << name << "! "; }; 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) << " "; // Capture by reference — modifies outer variable int count = 0; auto increment = [&count]() { ++count; }; increment(); increment(); increment(); std::cout << "count = " << count << " "; // 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 << " "; // 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) << " "; return 0; }
Result
Open