C++ Remove Algorithms: remove, unique & the Erase–Remove Idiom
이 글의 핵심
How remove algorithms relocate elements and why you must pair them with erase for real deletion.
Introduction
remove algorithms do not shrink the container — they compact elements and return an iterator to the new logical end. erase from there to end() actually removes excess elements.
1. remove
Typical pattern:
v.erase(std::remove(v.begin(), v.end(), value), v.end());
2. remove_if
Same pattern with a predicate (e.g. remove even numbers).
3. unique
Requires sorted order (or at least equal duplicates adjacent) to remove all duplicates globally — usually sort then unique then erase.
4. Examples
String whitespace cleanup, product filtering, duplicate removal — code matches Korean article; use erase-remove on std::string too.
5. Common pitfalls
- forgetting erase — stale size and junk tail values.
- unique without sort — only adjacent duplicates removed.
- multiple passes — combine conditions in one
remove_ifwhen possible. - list —
list::remove/remove_ifmember may be more appropriate (splice, no shifting).
6. C++20 std::erase / std::erase_if
Container-level erase helpers for brevity:
std::erase(v, 2);
std::erase_if(v, [](int x) { return x % 2 == 0; });
7. DataCleaner utility
The DataCleaner example (empty strings, duplicates, out-of-range, whitespace, normalize spaces) is unchanged in logic from the source article.
Summary
| API | Behavior | Typical use |
|---|---|---|
| remove | value != kept | Erase-remove idiom |
| remove_if | pred false kept | Conditional erase |
| unique | adjacent dupes | After sort |
| erase | actually deletes | After remove |
Next steps
- C++ Algorithm Replace
- C++ Algorithm Copy
- C++ Algorithm Sort
Related posts
- C++ Algorithm Copy
- C++ Algorithm Guide
Keywords
std::remove, remove_if, unique, erase-remove, std::erase, STL