溫馨提示×

如何在C++中使用copy_if與lambda表達式結(jié)合

c++
小樊
81
2024-09-25 01:29:14
欄目: 編程語言

在 C++ 中,std::copy_if 是一個算法,用于從一個輸入范圍復(fù)制滿足特定條件的元素到輸出范圍

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
    // 初始化一個整數(shù)向量
    std::vector<int> input = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    // 創(chuàng)建一個新的向量,用于存儲滿足條件的元素
    std::vector<int> output;

    // 使用 lambda 表達式定義條件:將偶數(shù)復(fù)制到輸出向量中
    auto condition = [](int num) { return num % 2 == 0; };

    // 使用 copy_if 算法將滿足條件的元素從輸入向量復(fù)制到輸出向量
    std::copy_if(input.begin(), input.end(), std::back_inserter(output), condition);

    // 輸出結(jié)果
    std::cout << "Output vector: ";
    for (int num : output) {
        std::cout << num << " ";
    }

    return 0;
}

在這個示例中,我們首先定義了一個輸入向量 input,然后創(chuàng)建了一個新的向量 output 用于存儲滿足條件的元素。接下來,我們定義了一個 lambda 表達式 condition,用于檢查一個整數(shù)是否為偶數(shù)。最后,我們使用 std::copy_if 算法將滿足條件的元素從輸入向量復(fù)制到輸出向量,并使用 std::back_inserter 作為目標(biāo)范圍的插入迭代器。運行此程序?qū)⑤敵鲆韵陆Y(jié)果:

Output vector: 2 4 6 8

0