How to iterate over an STL set and selectively delete elements?

The following code does not work correctly. How should this be done correctly?

for (std::set<Color>::iterator i = myColorContainer.begin(); i!=myColorContainer.end(); ++i) { if ( *i == Yellow) { DoSomeProccessing( *i ); myColorContainer.erase(i); } } 
+7
c ++ set stl
source share
3 answers

You do not need a loop when you work with a set.

 std::set<Color>::iterator it = myColorContainer.find(Yellow); if (it != it.myColorContainer.end()){ DoSomeProcessing(*it); myColorContainer.erase(it); } 
+6
source share

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++; } } 
+7
source share
 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; } } 

As soon as you move on to the next c ++i post, it will be valid - the std::set property, so that iterators on the inserted elements are never invalidated, unless the element is deleted.

So now you can safely erase the previous entry.

+2
source share

All Articles