如何从集合中删除所有偶数<int>在 C++ 中

2022-01-17 00:00:00 set c++ stdset

我是 C++ 新手.我想知道有经验的编码员是如何做到这一点的.

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

我有什么:

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

当然,它不起作用.因为它在擦除后递增.这是否意味着每次我从集合中删除元素后,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?

推荐答案

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

  else ++itr;
 }

Scott Myers 的有效 STL

effective STL by Scott Myers

相关文章