[英]Where is this code dereferencing an invalid iterator? (C++)
I have a loop 我有一个循环
for(aI = antiviral_data.begin(); aI != antiviral_data.end();)
{
for(vI = viral_data.begin(); vI != viral_data.end();)
{
if((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y)
{
vI = viral_data.erase(vI);
aI = antiviral_data.erase(aI);
}
else
{
vI++;
aI++;
}
}
}
But when ever antiviral_data contains an item, I get an error "vector iterator not dereferencable." 但是当antiviral_data包含一个项目时,我会收到错误“vector iterator not dereferencable”。 Why am I geting this error and where am I dereferencing an invalid iterator? 为什么我会发现此错误以及我在何处取消引用无效的迭代器?
NB: So far th error only occurs when the if() statement is false. 注意:到目前为止,仅当if()语句为false时才会发生错误。 I don't know what happens if the if() statement is true. 我不知道如果if()语句为真,会发生什么。
What are the sizes of the vectors? 矢量的大小是多少?
If viral_data has more elements then antiviral_data, then, since you increment aI and vI at the same rate, aI would go out of bounds before the vI loop would end. 如果viral_data有更多的元素然后是antiviral_data,那么,因为你以相同的速率增加aI和vI,所以aI会在vI循环结束之前超出界限。
Take a short example here: 举一个简短的例子:
for(int i = 0; i < 5;)
{
for(int j = 0; j < 10;)
{
i++;
j++;
}
}
If you go over the for loops, you'll notice that the inner loop will not end until both j and i are 10, but according to your outer loop, i should not be more then 5. 如果你越过for循环,你会注意到内循环不会结束,直到j 和 i都是10,但根据你的外循环,我不应该超过5。
You'll want to increment i (or in your case, aI) in the outer loop like so: 你会想要在外部循环中增加i(或者在你的情况下,aI),如下所示:
for(int i = 0; i < 5;)
{
for(int j = 0; j < 10;)
{
j++;
}
i++;
}
The dereferencing is happening at 解除引用正在发生在
((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y)
and it occurs when that statement is true for the last element in the antiviral_data
list. 并且当该语句对于antiviral_data
列表中的最后一个元素为真时发生。 In that case on the next iteration of the inner for loop you will be dereferencing antiviral_data.end()
which is not allowed. 在这种情况下,在内部for循环的下一次迭代中,您将取消引用不允许的antiviral_data.end antiviral_data.end()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.