這樣刪除會導致程序內存覆蓋等一系列不可預知的bug
map<string, string>::iterator iter;
for ( iter = mm.begin();iter != mm.end(); iter ++ )
{
if ( iter->second == something )
{
mm.erase( iter );
}
}
原因:當erase掉iter後,繼續執行iter++,這個時候就亂套了
正確方法:
for (iter = mm.begin();iter != mm.end();)
{
if ( iter->second == something )
{
mm.erase( iter++ );
}
else
{
iter++; // Use Pre Increment for efficiency.
}
}
可能有人不理解mm.erase(iter++)
其實和這個是一樣的
for (iter = mm.begin();iter != mm.end();)
{
if ( iter->second == something )
{
map<string, string>::iterator iter_erase;
iter_erase = iter++ //先保存後++再刪除
mm.erase( iter_erase );
}
else
{
iter++; // Use Pre Increment for efficiency.
}
}