How do I erase elements while iterating with std::vector for large datasets?

Iterating through a std::vector in C++ while erasing elements can be problematic, especially for large datasets. This is because removing elements can invalidate the iterator and lead to undefined behavior. To safely erase elements while iterating, you can use the erase-remove idiom or manually adjust the iterator. Here’s how you can do it:

iterating, std::vector, erase, elements, C++, large datasets, erase-remove idiom

This guide describes effective methods to iterate and erase elements in std::vector for large datasets without causing errors or performance issues.


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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Using the erase-remove idiom
    v.erase(std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());

    // Output the remaining elements
    for (int x : v) {
        std::cout << x << " ";
    }

    return 0;
}
    

iterating std::vector erase elements C++ large datasets erase-remove idiom