#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
auto makeMultiplier(int factor) {
return [factor](int x) { return x * factor; };
}
int main() {
auto greet = []() {
std::cout << "Hello from lambda!" << std::endl;
};
greet();
auto add = [](int a, int b) -> int {
return a + b;
};
std::cout << "add(3,4) = " << add(3, 4) << std::endl;
int multiplier = 10;
int copies = 0;
auto times = [multiplier, &copies](int x) {
copies++;
return x * multiplier;
};
std::cout << "times(5) = " << times(5) << std::endl;
std::cout << "copies = " << copies << std::endl;
int a = 2, b = 3;
auto sum = [=]() { return a + b; };
auto inc = [&]() { a++; b++; };
std::cout << "sum() = " << sum() << std::endl;
inc();
std::cout << "After inc: a=" << a << ", b=" << b << std::endl;
int count = 0;
auto mutableCounter = [count]() mutable {
return ++count;
};
std::cout << "mutableCounter(): " << mutableCounter() << std::endl;
std::cout << "mutableCounter(): " << mutableCounter() << std::endl;
std::cout << "External count still = " << count << std::endl;
std::vector<int> nums = {5, 2, 8, 1, 9, 3};
std::sort(nums.begin(), nums.end(), [](int x, int y) {
return x > y;
});
std::cout << "Sorted descending: ";
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
std::for_each(nums.begin(), nums.end(), [](int &n) {
n *= 2;
});
std::cout << "After doubling: ";
for (int n : nums) std::cout << n << " ";
std::cout << std::endl;
int threshold = 5;
int greaterCount = std::count_if(nums.begin(), nums.end(),
[threshold](int n) { return n > threshold; });
std::cout << "Count of elements > " << threshold << ": " << greaterCount << std::endl;
std::function<int(int, int)> func = [](int x, int y) {
return x * x + y * y;
};
std::cout << "func(3,4) = " << func(3, 4) << std::endl;
auto triple = makeMultiplier(3);
std::cout << "triple(5) = " << triple(5) << std::endl;
auto genericAdd = [](auto a, auto b) { return a + b; };
std::cout << "genericAdd(3, 5) = " << genericAdd(3, 5) << std::endl;
std::cout << "genericAdd(2.5, 1.5) = " << genericAdd(2.5, 1.5) << std::endl;
std::cout << "genericAdd(std::string(\"Hello, \"), \"world!\") = "
<< genericAdd(std::string("Hello, "), "world!") << std::endl;
int x = []() {
int val = 0;
for (int i = 1; i <= 10; ++i) val += i;
return val;
}();
std::cout << "Immediately invoked lambda sum 1..10 = " << x << std::endl;
return 0;
}