typedef map<string,int> MapFileList;
int main()
{
MapFileList m_SingleList; m_SingleList.insert(MapFileList::value_type("ttt", 0)); m_SingleList.insert(MapFileList::value_type("ddd", 1)); m_SingleList.insert(MapFileList::value_type("kkk", 0)); if (m_SingleList.size()>0)//是否保存了文件 { MapFileList::iterator tIter; int flag = 0; /*该写法是错误的,陷入了循环中 for(tIter = m_SingleList.begin(); tIter != m_SingleList.end(); tIter++) { cout<<tIter->first<<" -- "<<tIter->second<<endl; flag = tIter->second; if(flag> 0 ) { cout<<"erase "<<endl; m_SingleList.erase(tIter); } } */ for(tIter = m_SingleList.begin(); tIter != m_SingleList.end();) { flag = tIter->second; if (flag>0) m_SingleList.erase(tIter++); else { (*tIter).second = 1; ++tIter; } } /* 这个写法也可以通过的 for(tIter = m_SingleList.begin(); tIter != m_SingleList.end();) { flag = tIter->second; if (flag>0) tIter = m_SingleList.erase(tIter); else { (*tIter).second = 1; ++tIter; } }*/ }
}
分析:
在std::list中删除一个元素非常简单,直接使用erase方法即可,代码如下:
for(iter = list.begin(); iter != list.end();) { if (shouldDelete(*iter)) iter = list.erase(iter); else ++iter; }
或者更简单点
list.erase(std::remove_if(list.begin(), list.end(), shouldDelete), list_end());
然而根据STL std::map中的定义void erase(iterator pos),此erase并不返回下一个元素的迭代器,因此不能采用std::list的方法
for(iter = map.begin(); iter != map.end();) { if (shouldDelete(*iter)) map.erase(iter++); else ++iter; }
当然此方法同样也适合于std::list等