What is a lambda expression in C++ and when should it be used?
Hello colleagues! I started learning C++11 and keep coming across the term "lambda expression". I read the documentation, but I don't fully understand what it is and, most importantly, why it's needed.
Here's an example I found in a tutorial:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int multiplier = 3;
// What's happening here?
std::for_each(numbers.begin(), numbers.end(), [multiplier](int n) {
std::cout << n * multiplier << " ";
});
return 0;
}
I understand that `std::for_each` applies a function to each element, but the construct `[multiplier](int n) { ... }` confuses me. Why can't I just write