【问题标题】:What to do when erase fails to delete the element pointed to by the iterator? [closed]当erase删除迭代器指向的元素失败时怎么办? [关闭]
【发布时间】:2014-06-26 22:57:29
【问题描述】:

在以下代码中,我尝试擦除 templist 的特定元素。但是,仅删除列表的最后一个元素。如何删除该特定元素?

for(index1 = templist.begin(); index1 != templist.end();)
{
    checkit=templist.end();
    --checkit;

    if((*index1).origin == (*udit).dest && sumweight + (*index1).weight <= 25000)
    {
        sumhr += 1 + (*udit).hr;
        sumweight = sumweight + (*index1).weight;
        stops++;

        tour.at(i).push_back((*index1));

        if(index1! = checkit)
            index1 = templist.erase(index1);
        else
        {
            templist.erase(index1);
            index1 = templist.end();
        }
    }
    else
        index1++;
}

【问题讨论】:

  • 不清楚您的问题是什么以及您的代码做什么(或应该做什么)。你能把你的代码减少到足够复杂来说明你的问题吗?
  • 这个:templist.erase(index1); if(index1!=checkit) 不好,你刚刚删除了它!然后这个:index1++; 你在 for 循环减速和循环本身中增加 index1,你打算这样做吗?

标签: c++ list erase


【解决方案1】:

你问:

erase删除迭代器指向的元素失败怎么办?

不知道你是怎么得出这个结论的。一些支持该主张的数据会很有用。

但是,您对迭代器的使用存在一些问题。擦除元素后,您将迭代器递增两次。

建议的修复:

for(index1=templist.begin(); index1!=templist.end(); /* Don't increment the iterator here */ ) 
{
   if((*index1).origin==(*udit).dest && sumweight + (*index1).weight <=25000)
   {
      sumhr+=1+(*udit).hr;                         
      sumweight=sumweight+(*index1).weight;
      stops++;

      tour.at(i).push_back((*index1));

      // Erase the item and get the next iterator.
      index1 = templist.erase(index1);
   }
   else
   {
      // Increment the iterator only when we are not erasing.
      ++index1;
   }
}

【讨论】:

    【解决方案2】:

    您的问题是,从容器中删除元素后,迭代器无效。要解决此问题,您只需稍微更改逻辑即可。由于erase 函数返回一个迭代器,该迭代器引用容器中的下一个元素,您可以利用它来发挥自己的优势。具体如何在项目中执行此操作取决于您,但它应该像以下那样工作

    if (index1 != checkit)
    {
        // Remove the item. The iterator returned by "erase" is the next one
        // in line so there's no need to manually advance to the iterator with ++
        index1 = templist.erase(index1);
    }
    else
    {
        // Remove the item and skip to the end.
        templist.erase(index1);
        index1 = templist.end();
    }
    

    【讨论】:

    • 感谢您的帮助,我实施了这些更改,但仍然只能删除最后一个元素。我进一步上传了整个程序,可能漏洞就在那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 2019-11-22
    • 2018-10-18
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多