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

std::

replace_copy_if

函数模板  <algorithm>
template <class InputIterator, class OutputIterator, class UnaryPredicate, class T>
  OutputIterator replace_copy_if (InputIterator first, InputIterator last,
                                  OutputIterator result, UnaryPredicate pred,
                                  const T& new_value);

复制范围并检测替换部分值

将[first,last)范围内的元素复制到从result开始的范围,用new_value替换pred返回true的元素。

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


☲  参数


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

result
指向一个序列的初始位置的输出迭代器。范围包括与[first,last)一样多的元素。

指定的类型应该支持被赋值为类型T。

pred
一个一元函数,它接受范围中的一个元素作为参数,并返回一个可转换为bool的值。 返回的值指示在副本是否要替换元素(如果为true,则替换)。

函数不应修改参数。

它可以是函数指针,也可以是函数对象。

new_value
赋给被替换元素的值。
范围不得重叠。

☉  返回值



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

☣  示例



// replace_copy_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::replace_copy_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> foo,bar;

  // set some values:
  for (int i=1; i<10; i++) foo.push_back(i);          // 1 2 3 4 5 6 7 8 9

  bar.resize(foo.size());   // allocate space
  std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0);
                                                        // 0 2 0 4 0 6 0 8 0

  std::cout << "bar contains:";
  for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

输出:
second contains: 0 2 0 4 0 6 0 8 0

✥ 复杂度



first1和last1之间的距离线性:应用pred并对每个元素执行赋值。

⇄ 数据竞争


范围[first,last)中的对象将被访问。result 和返回值之间的对象被修改。

☂ 异常安全性



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

🍄  另请参阅



replace 替换范围内的值(函数模板)
transform 改变范围(函数模板)
remove_copy_if 复制范围内部分值(函数模板)
replace_copy 复制范围并替换部分值(函数模板)

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