Table of Contents

C++ Erase-remove

Erase-remove is the idiomatic way to remove elements matching a condition from a container: remove moves matching elements to the end and returns a new end iterator, then erase removes them. This avoids iterator invalidation issues and works with all standard containers.

Use the erase-remove idiom to safely and efficiently remove elements from containers.

Example

This example shows the erase-remove idiom removing elements by value and by condition.

// compile: g++ -o erase erase.cpp
// run: ./erase
// description: erase-remove idiom safely removes elements from containers
 
#include <iostream>
#include <vector>
#include <algorithm>
 
int main() {
    std::vector<int> v{1, 2, 3, 2, 4, 2, 5};
 
    // Remove all 2's using erase-remove
    v.erase(std::remove(v.begin(), v.end(), 2), v.end());
 
    // Remove all even numbers
    std::vector<int> v2{1, 2, 3, 4, 5, 6};
    v2.erase(
        std::remove_if(v2.begin(), v2.end(), 
                       [](int x) { return x % 2 == 0; }),
        v2.end()
    );
 
    std::cout << "After removal: ";
    for (int x : v2) std::cout << x << " ";
    std::cout << "\n";
 
    return 0;
}