问题描述
我有一个代码,其中我基本上有正值和负值。负值代表运算符('+'= - 1,' - '= - 2,'*'= - 3,'/'= - 4)我基本上必须要除以,得到总和等等负值前面的2个数字。
I have a code in which I basically have positive values and negative values. The negative values represent operators('+'=-1,'-'=-2,'*'=-3,'/'=-4) and I basically have to either divide, to make the sum and so on of the 2 numbers preceding the negative value.
std::list<long>::iterator i,j;
for(i=num.begin();++i!=num.end();)
{
if(*i<0&&num.size()>=2)
{
if(*i==-1)
{
*i=*--(j=i)+*----(j=i);
}
else if(*i==-2)
{
*i=*----(j=i)-*--(j=i);
}
else if(*i==-3)
{
*i=*--(j=i)**----(j=i);
}
else if(*i==-4&&*--(j=i)!=0)
{
*i=*----(j=i)/(*--(j=i));
}//this part is working properly
num.erase(--(j=i));
num.erase(--(j=i));//here is the only problem
break;
}
}
显然,我试图从中删除一个值不存在的列表。
Apparently, I am trying to erase a value from the list that doesn't exist.
推荐答案
撇开你的一些代码是未定义的行为并且完全不必要地隐藏的事实。
Stepping aside from the fact that some of your code is undefined behavior and completely unnecessarily cryptic.
std::list<long>::iterator i,j;
for(i=num.begin();++i!=num.end();)
{
// ...
num.erase(std::prev(i));
num.erase(std::prev(i));
}
我们知道 num.size()
> = = 2,但我们不知道 i
至少是2开始,所以实际上有两件事需要删除。你的第一次和/或第二次运行循环可能正在尝试擦除不存在的迭代器。
We know num.size()
>= 2, but we don't know that i
is at least 2 past begin so there are actually two things to erase. It's likely that your first and/or second runs through the loop are trying erase nonexistent iterators.
[edit]显然你的循环检查是 ++ i!= num.end()
。首先,不要这样做。其次,我猜这实际上意味着你开始一个过去的开始,所以这就是你在循环的第一次迭代中第二次擦除失败的原因:
[edit] Apparently your loop check is ++i != num.end()
. First, don't do that. Second, I guess that effectively means that you're starting one past begin, so that's why you fail on the 2nd erase in the first iteration of the loop:
[begin] <--> [item] <--> [item] <--> ...
^
i
您正试图删除这两项在 i
前面。只有一个。
You're trying to erase the two items in front of i
. There is only one.
这篇关于迭代器失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!