STL 迭代器 erase 的一个错误用法
2014-10-31 10:09
381 查看
今天检查出代码的一个异常,也怪自己太大意,习惯了ctrl+c/v。。描述如下:
map<UINT, CModule*> m_ModulePoints;for (map<UINT, CModule*>::iterator it = m_ModulePoints.begin(); it != m_ModulePoints.end(); it++){ CModule *pModule= (CModule*)(*it).second; if (.......) { delete pModule; m_ModulePoints.erase(it); } }那么问题来了,iterator it 被erase后,for循环仍旧对齐进行++操作,导致异常。在没有使用erase的情况下,我们确实可以使用这样的for循环结构遍历map,一旦需要erase,则不允许这样做。正确的做法之一:
for (map<UINT, CModule*>::iterator it = m_ModulePoints.begin(); it != m_ModulePoints.end(); ){ CModule *pModule= (CModule*)(*it).second; if (.......) { delete pModule; it = m_ModulePoints.erase(it); } else
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>it++;
<span style="white-space:pre"> </span>} }利用erase函数的返回值可以避免这一问题。另一种做法是:
for (map<UINT, CModule*>::iterator it = m_ModulePoints.begin(); it != m_ModulePoints.end(); ){ CModule *pModule= (CModule*)(*it).second; if (.......) { delete pModule; it = m_ModulePoints.erase(it++); } }
相关文章推荐
- [STL]list的erase正确与错误用法
- STL list erase 删除一个节点后,迭代器会失效吗
- [STL]list的erase正确与错误用法
- C++中防止STL中迭代器失效__map/set等关联容器vector/list/deque等序列容器_如何防止迭代器失效_即erase()的使用
- C++中防止STL中迭代器失效——map/set等关联容器——vector/list/deque等序列容器—如何防止迭代器失效—即erase()的使用
- STL容器的erase用法
- STL中erase()用法陷阱
- 关于STL的list,vector等用迭代器iterator,用erase删除元素出现的问题。
- PHP error_log()将错误信息写入一个文件(定义和用法)
- 解决一个很奇怪的STL错误
- 迭代器失效(1)-小心使用STL容器的erase()
- CLLocationCoordinate2D 用法 和一个最隐蔽的错误
- 使用STL时的一个链接错误(error LNK2005:std::_Lockit::_Lockit(int)重定义)
- STL_iterator迭代器(2)——几种迭代器对象的用法
- stl容器set,map,vector之erase用法与返回值详细解析
- C++中防止STL中迭代器失效__map/set等关联容器vector/list/deque等序列容器_如何防止迭代器失效_即erase()的使用
- 迭代器 stl map erase iterator 正确用法
- STL容器和迭代器用法归纳(3)
- 关于腾讯ip接口一个流传很广的错误用法
- STL的erase()陷阱-迭代器失效总结