算法copy_if( )的使用方法;
时间: 2024-02-16 12:00:12 浏览: 26
`copy_if()` 算法用于将满足指定条件的元素从一个容器复制到另一个容器中。以下是 `copy_if()` 算法的一般格式:
```c++
template<class InputIt, class OutputIt, class UnaryPredicate>
OutputIt copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred);
```
其中,`InputIt` 是源容器的迭代器类型,`OutputIt` 是目标容器的迭代器类型,`UnaryPredicate` 是一个函数对象类型,`pred` 是一个函数对象,用于判断源容器中的每个元素是否满足条件。
以下是一个示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool is_odd(int i) {
return i % 2 == 1;
}
int main() {
vector<int> v{1, 2, 3, 4, 5};
vector<int> v_odd;
// 使用 lambda 表达式作为函数对象
copy_if(v.begin(), v.end(), back_inserter(v_odd), [](int i) {
return i % 2 == 1;
});
// 使用全局函数作为函数对象
copy_if(v.begin(), v.end(), back_inserter(v_odd), is_odd);
// 输出目标容器的元素
for (int i : v_odd) {
cout << i << " ";
}
cout << endl;
return 0;
}
```
输出结果:
```
1 3 5
```
在上面的示例中,我们使用了 lambda 表达式和全局函数作为函数对象,分别将源容器中满足条件的元素复制到目标容器中。最后,我们输出目标容器的元素。注意,我们使用了 `back_inserter()` 函数来方便地向目标容器中添加元素。