Ugrás a tartalomhoz

Szerkesztő:LinguisticMystic/cpp/Lambdas

A Wikiszótárból, a nyitott szótárból

🔹 What Are Lambda Functions in C++?

[szerkesztés]

Lambda functions, also known as anonymous functions, are a powerful feature in C++ that allow you to define functions inline—right at the point where you need them. They’re particularly useful for short-lived tasks, such as callbacks, predicates in algorithms, or temporary computation logic.



🟩 Basic Syntax

[szerkesztés]
[capture](parameter_list) -> return_type {
    // function body
};

Explanation:

[szerkesztés]
  • capture: How you access external variables (by value [=] or by reference [&]).
  • parameter_list: Input arguments like in normal functions.
  • return_type (optional): Usually omitted; deduced automatically.
  • Function Body: Logic to execute when the lambda is called.



🟦 Getting Started: Hello World with Lambdas

[szerkesztés]

Traditional Function:

[szerkesztés]
void greet() {
    std::cout << "Hello world!" << std::endl;
}

Equivalent Lambda:

[szerkesztés]
[]() {
    std::cout << "Hello world!" << std::endl;
}();
  • The []() defines the lambda.
  • The final () calls it immediately.



🟧 Storing Lambdas in Variables

[szerkesztés]
auto multiplyByTen = [](int x) {
    return x * 10;
};
  • The auto keyword is essential because each lambda has a unique unnamed type.
  • Now you can call multiplyByTen(5) just like a normal function.



🟨 Capturing Variables

[szerkesztés]

🔹 By Value ([var])

[szerkesztés]

Captures a copy (read-only inside the lambda).

auto compare = [word](std::string other) {
    return word == other;
};

🔹 By Reference ([&var])

[szerkesztés]

Captures a reference (modifiable inside lambda).

auto increment = [&count]() {
    ++count;
};

🔹 All by Value ([=]) or All by Reference ([&])

[szerkesztés]
[=]() { /* read-only access to everything */ };
[&]() { /* read-write access to everything */ };

🟥 Captures: Warning about Dangling References

[szerkesztés]

Problematic Code:

[szerkesztés]
auto createLambda() {
    int x = 10;
    return [&]() { std::cout << x << std::endl; }; // ❌ x is destroyed after function returns
}
  • When x is referenced after it’s gone, it leads to undefined behavior.



🟫 Initializing Capture (C++14)

[szerkesztés]

Create and initialize variables inside the capture:

auto lambda = [y = x + 1]() {
    std::cout << y << std::endl;
};
  • Great for transforming values while capturing.



🟪 Universal Lambdas (C++20)

[szerkesztés]

Using auto in parameter list to make the lambda accept any type:

auto add = [](auto a, auto b) {
    return a + b;
};
  • Works with integers, floats, strings, etc.



🟨 Lambdas with STL Algorithms

[szerkesztés]

C++ STL makes extensive use of lambdas.

Example with sort, transform, for_each:

[szerkesztés]
std::sort(v.begin(), v.end(), [](int a, int b) { return a < b; });
std::transform(v.begin(), v.end(), out.begin(), [](int x) { return x / 2; });
std::for_each(out.begin(), out.end(), [](int x) { std::cout << x << " "; });
  • Lambdas provide inline behavior, making the code concise and expressive.



🟦 Summary Table

[szerkesztés]
Feature Syntax Example Notes
Basic Lambda []() { } Empty capture, no args
Store in variable auto f = []() { } Callable multiple times
Capture by value [x] Read-only copy of x
Capture by reference [&x] Allows modifying original x
Capture all by value [=] All outer variables as const copies
Capture all by reference [&] All outer variables by reference
Init capture (C++14) [y = x + 1] Defines and initializes y inside capture
Universal lambda (C++20) [](auto a, auto b) Accepts any types
Immediate execution []() { }(); Executes at point of definition



✅ Conclusion

[szerkesztés]

Lambda functions are:

  • Compact: Eliminate the need to define full functions for small tasks.
  • Powerful: Can capture context and be reused.
  • Essential in modern C++: Especially for STL algorithms, callbacks, and functional programming.

By mastering lambdas, you’ll write cleaner, safer, and more expressive C++ code.