Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...