🧹b. Erase-Remove Idiom


#intuition

The Erase-Remove Idiom is a technique used to remove elements from standard containers (like std::vector, std::list, etc.) using std::remove and container.erase().

Why?

Because std::remove doesn’t actually erase elements — it reorders them and returns a new logical end.

So:

remove moves

erase deletes


#use-case


#syntax + #example

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

int main() {
    std::vector<int> vec = {1, 2, 3, 2, 4, 2, 5};

    // Step 1: use std::remove
    // Step 2: use erase to actually delete them
    vec.erase(std::remove(vec.begin(), vec.end(), 2), vec.end());

    for (int x : vec) std::cout << x << " ";
    // Output: 1 3 4 5
}

With a condition (remove_if):

vec.erase(std::remove_if(vec.begin(), vec.end(), [](int x){ return x % 2 == 0; }), vec.end());

#pitfalls

Problem Description
❌ Misunderstanding std::remove It doesn’t actually remove — it reorders the valid elements and returns a new end.
❌ Iterator invalidation After remove, using iterators to erased elements is unsafe.
❌ Doesn’t work on associative containers Like std::map, std::set, where you must use their specific erase forms (erase_if in C++20).