erase删除迭代器所指向的元素失败时的处理方法
What to do when erase fails to delete the element pointed to by the iterator?
在下面的代码中,我尝试擦除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();
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- C++ std::向量插入两个元素替代算法失败
- Lambda 捕获数组元素失败
- 检查失败:1 == numelements()(1 vs. 1792)必须在Tensorflow C 中具有一个元素
- std::tuple的实现是否允许在触发空类元素的派生到基转换时失败
- 快速选择算法因元素重复而失败
- c++ sort() 函数对于<algorithm>整数数组的大小(元素数)>10^7 个元素的大输入是否失败?
- 返回指向指针数组的指针获取下一个元素失败
- 使用下标运算符进行Integer Vector元素比较失败,但使用at函数成功
- 映射写入失败:无法覆盖第一个元素
- erase删除迭代器所指向的元素失败时的处理方法
- 为什么std::vector::insert在VS2010中插入重复元素时失败
- 将元素追加到向量会导致后续排序失败
- 使用{0}的数组初始化失败,但某些编译器中的第一个元素除外
- Vector下标添加元素失败
- 为什么我的简单快速排序实现失败时,等效的元素在数组中