cpp / beginner
Snippet
Lambda Functions
Lambdas are anonymous functions defined inline. The syntax is [](parameters) -> returnType { body }. They are useful for short callbacks and predicates. The auto keyword captures the lambda type.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <algorithm>#include <vector>std::vector<int> nums = {5, 2, 8, 1, 9};std::sort(nums.begin(), nums.end(), [](int a, int b) {return a > b;});auto isEven = [](int n) -> bool {return n % 2 == 0;};std::cout << std::boolalpha << isEven(4);
Breakdown
1
[](int a, int b) { return a > b; }
Lambda acting as comparator for descending sort
2
auto isEven = [](int n) -> bool
Lambda assigned to variable with explicit return type
3
std::boolalpha << isEven(4)
Prints true because 4 is even