例子1:
1 1 std::list<item*>::iterator i = items.begin(); 2 2 while (i != items.end()) 3 3 { 4 4 bool isActive = (*i)->update(); 5 5 if (!isActive) 6 6 { 7 7 items.erase(i++); // alternatively, i = items.erase(i); 8 8 } 9 9 else 10 10 { 11 11 other_code_involving(*i); 12 12 ++i; 13 13 } 14 14 }
例子2:
1 for (std::list<int>::iterator itr = lst.begin(); itr != lst.end(); /*nothing*/) 2 { 3 if (*itr > 10) 4 itr = lst.erase(itr); 5 else 6 ++itr; 7 }
例子3:
1 for(vector<int>::iterator it=d.begin();it!=d.end(); ) 2 { 3 if(*it==3) 4 { 5 it=d.erase(it); 6 } 7 else 8 { 9 it++; 10 } 11 }