【问题标题】:c++ map erase function not working properly with iteratorc ++映射擦除功能无法与迭代器一起正常工作
【发布时间】:2013-06-22 03:37:59
【问题描述】:

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

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

【问题讨论】:

标签: c++ c++11


【解决方案1】:

来自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;
}

【讨论】:

    【解决方案2】:

    你应该这样做:

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

    【讨论】:

      【解决方案3】:
      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;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-05
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-30
        • 2018-09-09
        • 1970-01-01
        相关资源
        最近更新 更多