STL中的如此简单的常识现在才知道!!!

我的一段有关list中删除某一元素的代码:

RecorderList::iterator iter = recorders.begin();
 while (iter != recorders.end())
 {
  Recorder* item = (*iter);
  
  if (item->GetSpanSize() == 0)
  {
   wprintf(_T("%s :/n"),item->getRecordURI().c_str());
   item->Stop();      
   recorders.erase(iter);
  }
  else
      iter++; 

}

唉,我调试了半天才感觉是erase()的问题!!!后google和MSDN下才知道:

erase()执行后不会更新iterator 而是使它失效:

Remarks

No reallocation occurs, so iterators and references become invalid only for the erased elements.

erase never throws an exception.

所以要在erase()前更新iterator:

if (item->GetSpanSize() == 0)
  {
   wprintf(_T("%s :/n"),item->getRecordURI().c_str());
   item->Stop();      
   recorders.erase(iter++);
  }
  else
      iter++; 

你可能感兴趣的:(list,Google,iterator)