c ++ map erase功能与迭代器无法正常工作

nar*_*ren 0 c++ c++11

我通过以下方式使用擦除从地图中删除元素,但它无法正常工作.为什么?它并没有全部删除.

float nw_cut=80.0;
for(it=nw_tot1.begin();it!=nw_tot1.end();it++)
{
    float f=(float) ((float) it->second/lines)*100.0;
    if ( f < nw_cut )
    {
        nw_tot1.erase(it);
    }
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 6

来自std::map::erase():

擦除元素的引用和迭代器无效.其他引用和迭代器不受影响.

如果erase(it)被调用则it无效,然后由for循环使用它导致未定义的行为.存储返回值erase(),它将一个迭代器返回到擦除元素之后的下一个元素(从c ++ 11开始),并且仅erase()在未调用时递增:

for(it = nw_tot1.begin(); it != nw_tot1.end();)
{
    float f=(float) ((float) it->second/lines)*100.0;

    if ( f < nw_cut ) it = nw_tot1.erase(it);
    else ++it;
}
Run Code Online (Sandbox Code Playgroud)

在c ++ 03(以及c ++ 11)中,这可以通过以下方式实现:

for(it = nw_tot1.begin(); it != nw_tot1.end();)
{
    float f=(float) ((float) it->second/lines)*100.0;

    if ( f < nw_cut ) nw_tot1.erase(it++);
    else ++it;
}
Run Code Online (Sandbox Code Playgroud)