当erase无法删除迭代器指向的元素时怎么办? [英] What to do when erase fails to delete the element pointed to by the iterator?

查看:47
本文介绍了当erase无法删除迭代器指向的元素时怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the following code, I try to erase a specific element of templist. However, only the last element of the list is removed. How do I erase that specific element?

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

推荐答案

您问过:

如果擦除操作无法删除迭代器指向的元素,该怎么办?

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

不确定您是如何得出结论的.一些支持该主张的数据将是有用的.

Not sure how you concluded that. Some data supporting that claim would have been useful.

但是,您对迭代器的使用有点麻烦.删除元素后,您需要将迭代器增加两次.

However, your use of iterators is a little buggy. You are incrementing the iterator twice after you erase an element.

建议的解决方法:

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无法删除迭代器指向的元素时怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆