Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

copy_if

函数模板  <algorithm>
template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, InputIterator last,
                          OutputIterator result, UnaryPredicate pred);

复制范围的某些元素

将pred返回为true的范围[first,last]中的元素,复制到result开始的范围。

这个函数模板的行为相当于:
template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, InputIterator last,
                          OutputIterator result, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) {
      *result = *first;
      ++result;
    }
    ++first;
  }
  return result;
}

☲  参数


first, last
指向一个序列初始和最终位置的输入迭代器。使用的范围是[first,last), 它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

输入迭代器应指向一个类型,该类型可赋值给输出迭代器所指向的元素。
result
指向目标序列中的初始位置的输出迭代器。
范围包括与[first,last)一样多的元素。
pred
一个一元函数,它接受范围中的一个元素作为参数, 并返回一个可转换为bool的值。返回的值指示是否复制元素(如果为true,则复制它)。
函数不能修改它的任何参数。
它可以是函数指针,也可以是函数对象.
范围不得重叠。

☉  返回值



指向结果序列中最后一个元素后面的元素的迭代器.

☣  示例



// copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::copy_if, std::distance
#include <vector>       // std::vector

int main () {
  std::vector<int> foo = {25,15,5,-5,-15};
  std::vector<int> bar (foo.size());

  // copy only positive numbers:
  auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
  bar.resize(std::distance(bar.begin(),it));  // shrink container to new size

  std::cout << "bar contains:";
  for (int& x: bar) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;

输出:
bar contains: 25 15 5

✥ 复杂度



first and last之间的距离是线性的:将pred应用于范围内的每个元素,最多执行相同数量的赋值。

⇄ 数据竞争


访问[first,last)范围内的对象(每个对象只访问一次)。
result和返回值之间的对象被修改。

☂ 异常安全性



如果pred、元素赋值或迭代器上的任何操作抛出。,则抛出。
注意,无效的参数会导致未定义的行为。

🍄  另请参阅



copy 复制范围的元素(函数模板)
replace_copy_if 复制并检测替换范围内的值(函数模板)
remove_copy_if 检测并复制没有覆盖的元素(函数模板)

联系我们 免责声明 关于CandCplus 网站地图