STL 迭代器 erase 的一个错误用法

今天检查出代码的一个异常,也怪自己太大意,习惯了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++);
		}	
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值