how to remove all even integers from set<int> in c++

我的梦境 提交于 2019-11-29 09:50:19
 for(set<int>::iterator itr = s.begin(); itr != s.end(); ){
  if (!(*itr % 2))
      s.erase(itr++);

  else ++itr;
 }

effective STL by Scott Myers

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.

Mike Seymour

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

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!