溫馨提示×

能否用C++的copy_if實現(xiàn)自定義過濾

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

當(dāng)然可以!std::copy_if 是 C++ 標(biāo)準(zhǔn)庫中的一種算法,它可以根據(jù)指定的條件從一個范圍復(fù)制元素到另一個范圍

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

bool is_even(int num) {
    return num % 2 == 0;
}

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::vector<int> destination(source.size());

    std::copy_if(source.begin(), source.end(), destination.begin(), is_even);

    std::cout << "Even numbers from source: ";
    for (int num : destination) {
        std::cout << num << ' ';
    }
    std::cout << std::endl;

    return 0;
}

在這個示例中,我們定義了一個名為 is_even 的函數(shù),用于檢查一個整數(shù)是否為偶數(shù)。然后,我們創(chuàng)建了兩個向量:sourcedestination。我們使用 std::copy_ifsource 中的偶數(shù)復(fù)制到 destination 中。最后,我們輸出 destination 中的內(nèi)容,即 source 中的偶數(shù)。

0