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

时间:2013-06-25 11:05:17

标签: c++ c++11

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

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);
    }
}

3 个答案:

答案 0 :(得分: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;
}

在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;
}

答案 1 :(得分:1)

你应该这样做:

float nw_cut=80.0;
for(it=nw_tot1.begin();it!=nw_tot1.end();)
{
    float f=(float) ((float) it->second/lines)*100.0;
    it_temp = it;    //store it in temp variable because reference is invalidated when you use it in erase.
    ++it;
    if ( f < nw_cut ) {
        nw_tot1.erase(it_temp);
    }
}

答案 2 :(得分:0)

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;
}
相关问题