how to remove all even integers from set in c

2019-01-26 07:13发布

I'm new to C++. I'd like to know how experienced coders do this.

what I have:

set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(4);
s.insert(5);

for(set<int>::iterator itr = s.begin(); itr != s.end(); ++itr){
if (!(*itr % 2))
    s.erase(itr);
}

and of course, it doesn't work. because itr is incremented after it is erased. does it mean Itr has to point to the begin of the set everytime after i erase the element from the set?

标签: c++ set stdset
4条回答
时光不老,我们不散
2楼-- · 2019-01-26 07:37

Erasing an element from std::set only invalidates iterators pointing to that element.

Get an iterator to the next element before erasing the target element.

查看更多
放我归山
3楼-- · 2019-01-26 07:38
 for(set<int>::iterator itr = s.begin(); itr != s.end(); ){
  if (!(*itr % 2))
      s.erase(itr++);

  else ++itr;
 }

effective STL by Scott Myers

查看更多
The star\"
4楼-- · 2019-01-26 07:43

You don't need to go back to the start. set::erase only invalidates iterators that refer to the item being erased, so you just need to copy the iterator and increment before erasing:

for(set<int>::iterator itr = s.begin(); itr != s.end();)
{
    set<int>::iterator here = itr++;
    if (!(*here % 2))
        s.erase(here);
}
查看更多
聊天终结者
5楼-- · 2019-01-26 07:46

The best way is to use the combination of remove_if and erase

s.erase(remove_if(s.begin(), s.end(), evenOddFunctor), s.end())

This will be helpful http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Erase-Remove

Also Refer to effective STL by scott meyers

Edit: Although my solution is wrong i am not deleting it. It might be a good learning for someone like me who does not about mutable/immutable iterators

查看更多
登录 后发表回答