C++ Replace Algorithms: replace, replace_if & replace_copy

C++ Replace Algorithms: replace, replace_if & replace_copy

이 글의 핵심

Value and predicate replacement on ranges, plus copy variants that preserve the source.

Introduction

Replace algorithms substitute old values with new ones, or values matching a predicate, either in place or via copy variants.


std::replace / replace_if

Mutate the range in one linear pass.


std::replace_copy / replace_copy_if

Write results to d_first (often back_inserter) without changing the input.


Practical examples

Data cleaning (sensor errors), punctuation replacement, grade floors — same patterns as Korean article.


replace vs std::string::replace

  • <algorithm> std::replace: per-character / element replacement over iterators.
  • std::string::replace: substring API with positions/lengths — different overload set.

replace vs transform

  • replace: substitute specific value(s) or predicate matches.
  • transform: map every element with a function.

Common pitfalls

  • Multiple single-value replace passes → prefer one replace_if with combined condition.
  • Iterator validity: replace does not change container size — iterators often stay valid for vector (same slots).
  • Do not confuse with string::replace.

Summary

  1. replace — old value → new value
  2. replace_if — predicate → new value
  3. replace_copy — non-mutating copy path
  4. Time — O(n)

Next steps

  • C++ Algorithm Reverse
  • C++ Algorithm Remove

  • C++ STL algorithm basics

<|tool▁calls▁begin|><|tool▁call▁begin|> StrReplace