先看两条规制:1,对于节点式容器(map, list, set)元素的删除,插入操作会导致指向该元素的迭代器失效,其他元素迭代器不受影响2,对于顺序式容器(vector)元素的删除、插入操作会导致指向该元素以及后面的元素的迭代器失效常见的错误代码示例:
1struct sMem 2{ 3 int m_i; 4 sMem(int i = 10) 5 { 6 m_i = i; 7 } 8 9 int GetI()10 {11 return m_i;12 }13};
12typedef vector<sMem*> sMemList;3typedef vector<sMem*>::iterator sIT;4sMemList MemList;
1 // 迭代器失效 2 for (sIT it = MemList.begin(); it != MemList.end(); ++it) 3 { 4 if ((*it)->GetI() == 10) 5 MemList.erase(it); 6 else 7 { 8 printf("%d:%d\n", i++, (*it)->GetI()); 9 }10 }
两种解决方法:对于顺序容器:
bool Equal10(sMem* pMem){
return pMem->GetI() == 10 ? true : false;}
1MemList.erase(remove_if(MemList.begin(), MemList.end(), Equal10));
对于结点容器:
1 for (sIT it = MemList.begin(); 2 it != MemList.end(); ) 3 { 4 if ((*it).second->GetI() == 10) 5 MemList.erase(it++); 6 else 7 { 8 printf("%d:%d\n", i++, (*it).second->GetI()); 9 it++;10 }11 }
posted on 2009-07-09 14:48 肥仔 阅读(1555) 评论(0) 编辑 收藏 引用 所属分类: Boost & STL
Powered by: C++博客 Copyright © 肥仔