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

std::

replace

函数模板  <algorithm>
template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value);

替换范围内的值

将new_value赋给[first,last]范围内与old_value比较值相等的所有元素。

该函数使用operator==将各个元素与old_value进行比较。

这个函数模板的行为相当于:
template <class ForwardIterator, class T>
  void replace (ForwardIterator first, ForwardIterator last,
                const T& old_value, const T& new_value)
{
  while (first!=last) {
    if (*first == old_value) *first=new_value;
    ++first;
  }
}


☲  参数


first, last
指向一个支持比较和赋值为T类型序列的初始和最终位置的前向迭代器。 使用的范围是[first,last), 它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。

old_value
需要替换的值。

new_value
替换的值.

☉  返回值



none

☣  示例



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

int main () {
  int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
  std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20

  std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99

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

  return 0;
}

输出:
myvector contains: 10 99 30 30 99 10 10 99

✥ 复杂度



first1和last1之间的线性距离::比较每个元素并赋值给匹配的元素。

⇄ 数据竞争


范围[first,last)中的对象将被访问并可能被修改。

☂ 异常安全性



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

🍄  另请参阅



replace_if 检测并替换范围内的值(函数模板)
replace_copy 复制并比较替换范围内的值(函数模板)
remove 覆盖范围中的值(函数模板)
count 返回范围内某个元素的数量(函数模板)
find 在范围内查找值(函数模板)

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