The code:
for(x=abc.begin();x!=abc.end();x++)
{
if(-----)
{
----
abc.erase(x);
}
}
And the error is :::
Dangerous iterator usage
After erase the iterator is invalid so dereferencing it or comparing it with another iterator is invalid.
what is the wrong usage in using erase function in the above code?
The itarator x is invalid after deleting the corresponding value from abc. This should fix it:
x = abc.begin();
while(x != abc.end())
{
if (-----)
{
----
x = abc.erase(x);
// skipped only to next item
}
else
{ // skip only to next item
++x;
}
}
The erase
template functions of STL containers return the next element, or end()
.
Edit: Thanks for comment by templatetypedef.
You're using x as the control variable in the loop. Since it is invalidated by erase(), you cannot be sure that it is safe (or meaningful) to subsequently increment it at the top of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With