C++のラムダ式の応用法

C++ではラムダ式とは匿名関数を生成するための特別な構文です。これにより、必要な場所で関数オブジェクトを関数名を明示せずにインラインで定義できます。

以下に、よくあるラムダ表現の利用例をいくつか示します:

関数のパラメータとして

#include 
// lambda作为函数参数
void performOperation(int a, int b, std::function<int(int, int)> operation) {
    int result = operation(a, b);
    std::cout << "结果为:" << result << std::endl;
}
int main() {
    int x = 10;
    int y = 5;
    // 使用lambda作为函数参数
    performOperation(x, y, [](int a, int b) {
        return a + b;
    });
    return 0;
}</int(int, int)>

アルゴリズムに使用する

#include 
#include 
#include 
int main() {
    std::vector numbers = {5, 3, 8, 2, 1, 9};
    // 使用lambda表达式进行排序
    std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
        return a < b;
    });
    // 打印排序后的结果
    for (int num : numbers) {
        std::cout << num << " ";
    }
    return 0;
}

外部変数を捕捉する:

#include 
int main() {
    int x = 5;
    int y = 10;
    // 使用lambda表达式捕获外部变量
    auto sum = [x, y]() {
        return x + y;
    };
    std::cout << "和为:" << sum() << std::endl;
    return 0;
}

これらの例は、C++におけるラムダ式をどのように使用するかという一般的な方法をいくつか示しています。特定のニーズに応じて、ラムダ式を適切な場所で利用して匿名関数を简洁に定義できます。

bannerAds