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
replacepasses → prefer onereplace_ifwith 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
- replace — old value → new value
- replace_if — predicate → new value
- replace_copy — non-mutating copy path
- Time — O(n)
Next steps
- C++ Algorithm Reverse
- C++ Algorithm Remove
Related posts
- C++ STL algorithm basics
<|tool▁calls▁begin|><|tool▁call▁begin|> StrReplace