12

How can I remove elements from an std::set while iterating over it

My first attempt looks like:

set<T> s;

for(set<T>::iterator iter = s.begin(); iter != s.end(); ++iter) {
    //Do some stuff
    if(/*some condition*/)
        s.erase(iter--);
}

But this is problematic if we want to remove the first element from the set because iter-- invalidates the iterator.

What's the standard way to do this?

Evert Heylen
  • 960
  • 9
  • 28
dspyz
  • 5,280
  • 2
  • 25
  • 63

1 Answers1

26

Standard way is to do something like

for(set<T>::iterator iter = s.begin(); iter != s.end();)
{
   if(/*some condition*/)
   {
      s.erase(iter++);
   }
   else
   {
      ++iter;
   }
}

By the first condition we are sure, that iter will not be invalidated anyway, since a copy of iter will be passed into erase, but our iter is already incremented, before erase is called.

In C++11, the code will be like

for(set<T>::iterator iter = s.begin(); iter != s.end();)
{
   if(/*some condition*/)
   {
      iter = s.erase(iter);
   }
   else
   {
      ++iter;
   }
}
stafusa
  • 195
  • 1
  • 15
ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 1
    The first peice of code fails an assertion saying that the iterators are incompatible in visual studion. Anyway, std::erase returns the new iterator, as you pointed out in your code. – sajas Dec 17 '13 at 06:53
  • The second code works for me. – Larynx Jun 17 '22 at 08:15