Quick Answer
Create anonymous functions in C++.
Understanding the Issue
Lambdas allow defining function objects inline, especially useful with STL algorithms. They can capture variables from their enclosing scope.
The Problem
This code demonstrates the issue:
Cpp
Error
// Need a short function for sorting
The Solution
Here's the corrected code:
Cpp
Fixed
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> numbers = {4, 2, 5, 1, 3};
// Lambda for custom sorting
std::sort(numbers.begin(), numbers.end(),
[](int a, int b) {
return a > b; // Descending order
});
// Lambda with capture
int threshold = 3;
auto count = std::count_if(numbers.begin(), numbers.end(),
[threshold](int n) {
return n > threshold;
});
std::cout << count << " numbers > " << threshold << std::endl;
return 0;
}
Key Takeaways
Lambdas provide concise syntax for inline function objects.