Core Module
12 min forge
C++ Lambda Functions
Understanding anonymous functions for concise and powerful functional programming.
C++ Lambda Functions
π What is it
Lambda functions are anonymous functions that you can define in-place within your code. They are objects that can be called, stored, and passed as arguments just like regular functions.
β‘ When to use
Perfect for use as predicates for STL algorithms (like std::sort or std::find_if), and for defining short callback functions without cluttering the global namespace.
π§ Time complexity
- Creation: $O(1)$.
- Call: $O(1)$ (compiler usually inlines them).
π» Code example
cpp Standardauto add = [](int a, int b) { return a + b; }; std::cout << add(1, 2); // 3 std::vector<int> v = {3, 1, 2}; std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; // Descending order });
β Common mistakes
- Capture Errors: Forgetting to capture necessary variables (
[=]or[&]). - Dangling References: Capturing local variables by reference and using the lambda after the variables have gone out of scope.
- Over-complicating: Using lambdas for very complex logic that should probably be a regular function for better readability.