• Advertisement
Sign in to follow this  

std::set question

This topic is 4682 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi All, Question on std::set<> stuff: how do iterators behave when one does erase's? example:
  std::set<int> mySet;

  //put stuff into mySet

  while(!mySet.empty())
  {
     std::set<int>::iterator iter;

     iter=mySet.begin();
     while(iter!=mySet.end())
     {
        int value;

        value=*iter;
        if (TakeValueFromSet(value))
         {
             ++iter;
             //do stuff with value,
             mySet.erase(value);
         }
        else
            ++iter;
          
     }
  }



basicly I am breaking a large set into smaller pieces... the idea being that I want to eventually empty the original set, mySet... now the call: ++iter; goes to the next element of mySet.. but do all iterators get invalidated after an erase command? if so would the correct way to do this would be:
if (TakeValueFromSet(value))
         {
             //do stuff with value,

             
             if (iter!=mySet.end())
             {
                 nextValue=*iter;
                 mySet.erase(value);
                 iter=mySet.find(nextValue);
             }
             else
             {
                 mySet.erase(value);
                 iter=mySet.end();
             }

             
             
         }
   


but in that case, does iter really point to what the "next" element of the set would be? can one assume that when one access'es elements of a set with iterators via begin()/end() that one gets them in order? Best Regards

Share this post


Link to post
Share on other sites
Advertisement
You should probably do your erasing using an iterator.

Anyway, the iterators for std::set are guaranteed not to get invalidated when inserting or erasing, with the exception of iterators pointing to the element you're erasing.

Share this post


Link to post
Share on other sites
oh good that is good news! when I first wrote I did this:

oldIter=iter;
++iter;
mySet.erase(oldIter);

good beans for me that it is ok.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement