Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

c++ - How to remove elements from an std::set while iterating over it

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...