Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

set

stdset

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?

like image 382
Quincy Avatar asked Jan 18 '10 19:01

Quincy


1 Answers

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

  else ++itr;
 }

effective STL by Scott Myers

like image 198
pm100 Avatar answered Oct 10 '22 03:10

pm100