How do I erase elements while iterating with std::vector in multithreaded code?

C++, std::vector, multithreaded code, erase elements, threading
This article discusses how to safely erase elements from a std::vector while iterating in a multithreaded environment.

#include <iostream>
#include <vector>
#include <thread>
#include <mutex>

std::vector<int> vec = {1, 2, 3, 4, 5};
std::mutex mtx;

void removeEvenNumbers() {
    std::lock_guard<std::mutex> lock(mtx);
    vec.erase(std::remove_if(vec.begin(), vec.end(), [](int n) { return n % 2 == 0; }), vec.end());
}

int main() {
    std::thread t1(removeEvenNumbers);
    t1.join();

    for (int n : vec) {
        std::cout << n << " ";
    }
    return 0;
}
    

C++ std::vector multithreaded code erase elements threading