Domanda

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"));
}
È stato utile?

Soluzione

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

Make it:

it = a.erase(it);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top