The code:
for(x=abc.begin();x!=abc.end();x++)
{
if(-----)
{
---- 开发者_JS百科
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.
x
is a pointer into abc
. Once you've erased the item pointed to by x
, what is x
supposed to be pointing to and how is x++
supposed to work?
You said nothing about the container you are iterating on. On the type of the container depends which iterators are invalidated. For sure iterator to erased element is invalid, but for example in std::vector
all iterators past erased element will be invalid (including end()
). And for unknown reason although set::erase
invalidates only iterator to erased element, it does not return the iterator to next element.
So with std::set
:
while (x != abc.end()) // end() will not change and even can be stored
{
if (...)
abc.erase(x++); // increments before erasing
else
++x;
}
精彩评论