溫馨提示×

能否用C++的copy_if實現(xiàn)元素的間接復(fù)制

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

是的,你可以使用 C++ 的 std::copy_if 算法來實現(xiàn)元素的間接復(fù)制。下面是一個簡單的示例代碼:

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

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

    // 使用 copy_if 和 lambda 表達式復(fù)制 source 中的偶數(shù)元素到 destination 中
    std::copy_if(source.begin(), source.end(), destination.begin(),
                 [](int value) { return value % 2 == 0; });

    // 輸出 destination 中的元素
    for (int value : destination) {
        std::cout << value << ' ';
    }

    return 0;
}

在上面的示例中,我們定義了兩個 std::vector 對象:sourcedestination。然后,我們使用 std::copy_if 算法將 source 中的偶數(shù)元素復(fù)制到 destination 中。在 std::copy_if 的第四個參數(shù)中,我們使用了一個 lambda 表達式來指定復(fù)制條件。如果 value 是偶數(shù),則將其復(fù)制到 destination 中。

最后,我們輸出 destination 中的元素,以驗證元素的間接復(fù)制是否成功。

0