std::advance - 仅在调试时偏移超出范围故障

std::advance - offset out of range failure on Debug only

我正在尝试使用 std::advance 对向量进行 1 次以上的迭代。 Debug 和 Release 构建之间存在差异,Debug 导致向量迭代器 + 偏移量超出范围失败,而 Release 即使在更扩展的情况下的实际应用程序中也能正常工作。为什么会发生这种情况,我该如何编写它才能在 Debug 上运行?

vector<glm::vec2> testV;
testV.push_back(glm::vec2(0.f));
int step = 2;

for (auto it = testV.begin(); it != testV.end(); )
{
    if (it + step <= testV.end())
        advance(it, step);

    else
        ++it;
}

这也在 Release 上运行(除非我在循环中打印一些东西导致挂起)

for (auto it = testV.begin(); it != testV.end(); )
    advance(it, step);

迭代器的加法运算符正在验证返回的迭代器。当您添加 2 并越过末尾时,这将在调试中产生错误。发布版本没有这些检查,因此不会报告问题。

我认为让迭代器指向容器末尾是未定义的行为。取消引用肯定是。

您必须以其他方式检查是否超过终点。