Replaces elements that have a special value with another value

You're viewing an older version of this page (#4135). View the current version.

View versions (1)

Definition

The replace() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator, class Type >
   void replace(
      ForwardIterator first, 
      ForwardIterator last,
      const Type& oldVal, 
      const Type& newVal
   );

Parameters:

ParameterDescription
firstA forward iterator pointing to the position of the first element in the range from which elements are being replaced
lastA forward iterator pointing to the position one past the final element in the range from which elements are being replaced
oldValThe old value of the elements being replaced
newValThe new value being assigned to the elements with the old value

Description

Replace function replaces all value equal to oldVal (using operator== of the iterator) by the value newVal in a range. The replacement is done by using operator= of the iterator.

Return Value

None.

Complexity

The complexity is linear; there are (last - first) comparisons for equality and at most (last - first) assignments of new values.

References

Example 1
Problem

This program illustrates the use of the STL replace() algorithm to replace all copies of a given value from a vector of integers with another value.

Workings
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
  int a[] = {1, 2, 2, 3, 4, 5, 2, 3};
  vector<int> v(a, a+8);

  cout <<"\nHere are the values in the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  cout <<"\nNow we replace all copies of the value 2 with 222.";
  replace(v.begin(), v.end(), 2, 222);

  cout <<"\nHere are the revised contents of the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";

  return 0;
}
Solution

Output:

Here are the values in the vector:
1 2 2 3 4 5 2 3

Now we replace all copies of the value 2 with 222.

Here are the revised contents of the vector:
1 222 222 3 4 5 222 3

See Also