简体   繁体   English

为什么 C++ 在这里抛出一个超出范围的错误?

[英]Why C++ throws an out of range error here?

I really cannot find the reason why here a "cannot seek vector iterator after end" error occurs.我真的找不到为什么会出现“结束后无法寻找向量迭代器”错误的原因。 I cannot show the whole code but I think that this part should be enough:我无法显示整个代码,但我认为这部分应该足够了:

qDebug() << Pun.size() << ", " << 2*pos - counter;
Pun.erase(Pun.begin() + 2*pos - counter); //the error seems to happen here
qDebug() << "B";
Pun.erase(Pun.begin() + 2*pos - counter);
counter += 2;

When I run my code, the last what is printed is "4, 1" and the "B" is not printed so it has to be in the line above but it can't if Pun.size() is 4 and 2*pos - counter is 1.当我运行我的代码时,最后打印的是“4, 1”并且没有打印“B”所以它必须在上面的行中但是如果 Pun.size() 是 4 和 2* pos - 计数器为 1。

Maybe this helps: This is part of a big algorithm for a special problem and I run into this problem when I tested the program on a lot of instances.也许这有帮助:这是针对一个特殊问题的大算法的一部分,当我在很多实例上测试该程序时遇到了这个问题。 I traced down the error to a special instance and the weird thing is that when I run the algorithm the first time this error doesn't occur but when it's done the second time it somehow does....我将错误追溯到一个特殊的实例,奇怪的是,当我第一次运行算法时,这个错误没有发生,但是当它第二次运行时,它以某种方式发生了……

Any hint would be really helpful...任何提示都会非常有帮助......

Operator precedence problems -- + and - are the same precedence (and are left-recursive), so your erase call is really运算符优先级问题 -- +-是相同的优先级(并且是左递归的),所以你的 erase 调用真的

Pun.erase((Pun.begin() + 2*pos) - counter);

which probably tries to advance well past the end of Pun , causing it to throw an exception.这可能会试图远远超过Pun的末尾,导致它抛出异常。 I'm assuming here Pun is some custom sequence type that does bounds checking (ie, not std::vector).我在这里假设Pun是一些进行边界检查的自定义序列类型(即,不是std::vector)。 You want你要

Pun.erase(Pun.begin() + (2*pos - counter));

you mean你的意思是

Pun.erase(Pun.begin() + (2*pos - counter)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM