Question

I run my code in debug mode, and the program pops up a assertion failed message. Please help me find which part leads to this assertion failure. :{

Debug Assertion Failed!
Expression: vector iterators incompatible

Code:

int main()
{
vector<int> a(5);
fill(a.begin(), a.end(), 5);
a[2] = 3;
a[1] = 2;  //so now a = {5,2,3,5,5} 

auto it = a.begin();
for (; it != a.end();)
{
    if (*it == 5)
        a.erase(it);  //Remove 5
    else
        it++;
}
copy(a.begin(), a.end(), ostream_iterator<int>(cout, "\n"));
}
Was it helpful?

Solution

When you erase during iteration the erased iterator becomes (and other may become) invalid:

Make it:

it = a.erase(it);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top