温馨提示×

能否用C++的copy_if实现自定义过滤

c++
小樊
94
2024-09-25 01:21:14
栏目: 编程语言

当然可以!std::copy_if 是 C++ 标准库中的一种算法,它可以根据指定的条件从一个范围复制元素到另一个范围

#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 的函数,用于检查一个整数是否为偶数。然后,我们创建了两个向量:sourcedestination。我们使用 std::copy_ifsource 中的偶数复制到 destination 中。最后,我们输出 destination 中的内容,即 source 中的偶数。

0