目录

algorithm::copy_if()

描述 (Description)

如果谓词为值返回true,则C ++函数std::algorithm::copy_if()将一系列元素复制到新位置。

声明 (Declaration)

以下是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);

参数 (Parameters)

  • first - 将迭代器输入到搜索序列的初始位置。

  • last - 将迭代器输入到搜索序列的最终位置。

  • result - 将迭代器输出到新序列中的初始位置。

  • pred - 一元谓词,它接受一个参数并返回一个bool值。

返回值

返回一个迭代器,指向结果序列中写入的最后一个元素后面的元素。

异常 (Exceptions)

如果元素赋值或迭代器上的操作抛出异常,则抛出异常。

请注意,无效参数会导致未定义的行为。

时间复杂

第一个最后一个之间的距离线性。

例子 (Example)

以下示例显示了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
↑回到顶部↑
WIKI教程 @2018