Namara

Code daily. Without assist.

2026-08-20

remove_negatives.cpp

#include <vector>

void remove_negatives(std::vector<int>& v) {
    for (auto it = v.begin(); it != v.end(); ++it) {
        if (*it < 0) {
            v.erase(it);
        }
    }
}

This has a bug that shows up on inputs with more than one negative number. Find it and fix it.

Answer

v.erase(it) invalidates it; the loop's ++it then increments an invalidated iterator — undefined behavior. erase already returns a valid iterator to the next element, so use that instead of blindly incrementing:

for (auto it = v.begin(); it != v.end(); ) {
    if (*it < 0) it = v.erase(it);
    else ++it;
}