Avatar ·

What is a lambda expression in C++ and when should it be used?

Hello everyone! I'm learning C++ and often see something like this in my colleagues' code:\n\n```cpp\nstd::vector numbers = {5, 2, 8, 1, 9};\nstd::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; });\n```\n\nOr like this:\n\n```cpp\nstd::for_each(numbers.begin(), numbers.end(), [](int& x) { x *= 2; });\n```\n\nI understand these are some kind of anonymous functions, but I don't fully understand them. The documentation says "lambda expressions", but the explanations are somewhat complicated. I have several questions:\n\n1. What is a lambda expression in simple terms? How is it different from a regular function?\n2. Why are the square brackets `[]` needed at the beginning? What can be written inside them?\n3. When is it better to use a lambda, and when a regular function or functor?\n4. How to properly capture variables? I've seen `[=]`, `[&]`, `[`