erase删除迭代器所指向的元素失败时的处理方法

What to do when erase fails to delete the element pointed to by the iterator?

本文关键字:元素 失败 处理 方法 删除 迭代器 erase      更新时间:2023-10-16

在下面的代码中,我尝试擦除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++;
}

你问:

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

您的问题是,从容器中删除元素后,迭代器无效。要解决这个问题,你只需要稍微改变一下你的逻辑。由于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();
}