The following code does not work correctly. How should it be done correctly?
for (std::set<Color>::iterator i = myColorContainer.begin();
i!=myColorContainer.end();
++i)
{
if ( *i == Yellow)
{
DoSomeProccessing( *i );
myColorContainer.erase(i);
}
}
Try:
for(std::set<Color>::iterator it = myColorContainer.begin();
it != myColorContainer.end();) { // note missing it++
if( (*it) == Yellow ) {
DoSomeProcessing(*it);
myColorContainer.erase(it++); // post increment (original sent to erase)
}
else {
++it; // more efficient than it++;
}
}
You don't need a loop as youre dealing with a set.
std::set<Color>::iterator it = myColorContainer.find(Yellow);
if (it != it.myColorContainer.end()){
DoSomeProcessing(*it);
myColorContainer.erase(it);
}
for (std::set<Color>::iterator i = myColorContainer.begin();
i!=myColorContainer.end(); /* No i++ */)
{
if ( *i == Yellow)
{
DoSomeProccessing( *i );
std::set<Color>::iterator tmp = i;
++i;
myColorContainer.erase(tmp);
}
else {
++i;
}
}
Once you go to next message with ++i
it is guaranteed to be valid - property of std::set
that iterators on inserted elements are never invalidated unless the element
is removed.
So now you can safely erase previous entry.
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