您的位置:首页 > 其它

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++);		}		}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: