Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Lambda Expressions | Functional Programming
C++ Modern Features

bookLambda Expressions

メニューを表示するにはスワイプしてください

Lambda expressions in modern C++ allow you to define anonymous functions directly in your code. They are especially useful for short, inline operations such as sorting, filtering, or customizing algorithms. The basic syntax of a lambda is [capture](parameters) { body }. The capture clause lets you specify which variables from the surrounding scope the lambda can access. You can capture variables by value using = or by reference using &. For example, [=] captures all needed variables by value, while [&] captures all by reference. You can also specify individual variables, such as [x, &y]. Lambdas can be assigned to variables, passed to functions, or used immediately where defined.

main.cpp

main.cpp

copy
1234567891011121314151617181920212223242526
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers{1, 2, 3, 4, 5, 6}; int count = 0; // Lambda to filter even numbers, capturing 'count' by reference and 'numbers' by value auto print_even = [&, numbers]() mutable { std::cout << "Even numbers: "; for (int n : numbers) { if (n % 2 == 0) { std::cout << n << " "; ++count; // count is captured by reference } } std::cout << "\n"; }; print_even(); std::cout << "Total even numbers: " << count << "\n"; }

Lambdas are ideal when you want concise, readable code for operations used only once or in a limited scope, such as passing custom predicates to algorithms. However, you should be careful with captures. Accidentally capturing variables by reference can lead to bugs if the referenced variable goes out of scope, while capturing by value may not reflect changes to the original variable. Always choose the capture mode that matches your intent.

question mark

Which statement about lambda expressions in C++ is true?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  1

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  1
some-alt