capypad
0 Tage Serie
cpp / beginner
Snippet

Lambda-Funktionen

Lambdas sind anonyme Funktionen, die inline definiert werden. Die Syntax ist [](parameters) -> returnType { body }. Sie sind nützlich für kurze Callbacks und Prädikate. Das auto-Schlüsselwort erfasst den Lambdatyp.

snippet.cpp
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);
Erklärung
1
[](int a, int b) { return a > b; }
Lambda als Komparator für absteigende Sortierung
2
auto isEven = [](int n) -> bool
Lambda einer Variable mit explizitem Rückgabetyp zugewiesen
3
std::boolalpha << isEven(4)
Gibt true aus, weil 4 gerade ist