温馨提示×

能否用C++的copy_if实现元素的间接复制

c++
小樊
81
2024-09-25 01:31:13
栏目: 编程语言

是的,你可以使用 C++ 的 std::copy_if 算法来实现元素的间接复制。下面是一个简单的示例代码:

#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 表达式复制 source 中的偶数元素到 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 中的偶数元素复制到 destination 中。在 std::copy_if 的第四个参数中,我们使用了一个 lambda 表达式来指定复制条件。如果 value 是偶数,则将其复制到 destination 中。

最后,我们输出 destination 中的元素,以验证元素的间接复制是否成功。

0