C++ Algorithm 库 - copy_if() 函数
描述
C++ 函数 std::algorithm::copy_if() 如果谓词为值返回 true,则将一系列元素复制到新位置。
声明
以下是 std::algorithm::copy_if() 函数形式 std::algorithm 头的声明。
C++11
template <class InputIterator, class OutputIterator, class UnaryPredicate> OutputIterator copy_if(InputIterator first,InputIterator last, OutputIterator result,UnaryPredicate pred);
参数
first − 将迭代器输入到搜索序列的初始位置。
last − 将迭代器输入到搜索序列的最终位置。
result − 将迭代器输出到新序列中的初始位置。
pred − 一元谓词,它接受一个参数并返回一个布尔值。
返回值
返回一个迭代器,该迭代器指向在结果序列中写入的最后一个元素之后的元素。
异常
如果元素赋值或迭代器上的操作引发异常,则引发异常。
请注意,无效参数会导致未定义的行为。
时间复杂度
first 到 last 之间的距离呈线性关系。
示例
以下示例显示了 std::algorithm::copy_if() 函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool predicate(int n) {
return (n %2 != 0);
}
int main(void) {
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2(3);
copy_if(v1.begin(), v1.end(), v2.begin(), predicate);
cout << "Following are the Odd numbers from vector" << endl;
for (auto it = v2.begin(); it != v2.end(); ++it)
cout << *it << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Following are the Odd numbers from vector 1 3 5

