循环根据iterator删除相应元素的代码

来源:互联网 发布:cms集中管理软件下载 编辑:程序博客网 时间:2024/05/29 07:38

错误的方法:

  1. for (MAP::iterator it = theMap.begin(); theMap.end()!=it; ++it) {  
  2.     if (canDrop(*it)) {  
  3.         // 错误:当erase执行以后,it立刻就失效了,在执行到for循环的++it时就会出现未知后果。  
  4.         theMap.erase(it);  
  5.      }  
  6.  }
正确的方法:

  1. for (MAP::iterator it = theMap.begin(); theMap.end()!=it;) {  
  2.     if (canDrop(*it)) {  
  3.         // 在erase之前,先递增迭代器,此时由于erase尚未被调用,所以递增后的迭代器有效  
  4.         // 然后用迭代器的原始值来调用erase,确何删除正确的荐  
  5.         theMap.erase(it++);  
  6.     } else {  
  7.         ++it;  
  8.     }  
  9. }
原创粉丝点击