Name

replace_copy function template — Copies a range, replacing occurrences of one value with another value

Synopsis

template<typename InIter, typename OutIter, typename T>
  OutIter replace_copy(InIter first, InIter last, OutIter result, 
                       const T& old_value, const T& new_value);

The replace_copy function template copies values from [first, last) to the range that starts at result. Values that are equal to old_value are replaced with new_value; other values are copied without modification.

The return value is an iterator that points to one past the end of the result range. The source and result ranges must not overlap. Figure 13-14 illustrates the replacement process.

Replacing all occurrences of 42 with 10
Figure 13-14. Replacing all occurrences of 42 with 10

Technical Notes

The replace_copy function template assigns *(result + n) = *(first + n) == old_value ? new_value : *(first + n) for all n in [0, last - first).

Complexity is linear: exactly last - first comparisons are performed.

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.