使用三个向量的向量下标超出范围错误,我怎么知道哪个迭代错误

vector subscript out of range error using three vectors, how do I know which one is iterating wrong

您好,我正在尝试在 openframeworks 中用 c++ 实现 Diffusion Limited Aggregation 算法。我有一个 class ,我在其中定义了两个向量,称为 walkers 和 fixed ,分别包含死者和 living/moving 以及不移动的粒子。我的更新功能是这样的:

void DLA::update() {

// Permutation buffer
vector<int> buffer;

for (std::size_t i = 0; i != walkers.size(); ++i) // go through every main/alive particles
{
    walkers[i].update();

    for (std::size_t j = 0; j != fixed.size(); ++j) // go through every fixed/dead particles
    {
        float distance = walkers[i].position.distance(fixed[j].position); // calculate the distance between them
        if (distance < 5) // if the distance is small enough
        {
            buffer.push_back(i); // put the index of the alvie walker in buffer for deletion
        }
    }
}
// Apply buffered information
for (std::size_t i = buffer.size(); i != 0; --i)
{
    walkers[buffer[i]].randomWalk = 0; // make it dead
    fixed.push_back(walkers[buffer[i]]); // put it in the fixed/dead vector
    walkers.erase(walkers.begin() + buffer[i]); // take it out from the main alive vector
}
buffer.clear();

}

但是每次我 运行 我都会得到一个矢量下标超出范围的错误。不熟悉 c++ 和 visual studio,也不习惯依赖框架,我很难理解错误的来源,因为我找不到脚本中我正在编写的位置问题源于。编译器将我发送到属于基本 openframeworks class 代码的另一页代码,说明在那里检测到错误。

我已经开始进入调试模式,但从那里我看到的是我的 RandomWalker 数组的原始值。

我的代码有什么问题,我如何根据 Visual Studio 提供的信息清楚地诊断出这个问题?谢谢!

编辑:

在不使用缓冲区的情况下修复了它,只是 运行以相反的顺序通过两个向量

for (std::size_t i = walkers.size() - 1; i != -1; --i)
{
    for (std::size_t j = fixed.size() - 1; j != -1; --j) // go through every fixed/dead particles
    {
        // Calculate Distance
        float distance = walkers[i].position.distance(fixed[j].position); 

        if (distance < (walkers[i].radius + fixed[j].radius)) // if the distance is small enough
        {
            walkers[i].randomWalk = 0; // make it dead
            fixed.push_back(walkers[i]); // put it in the fixed/dead vector
            walkers.erase(walkers.begin() + i); // take it out from the main alive vector
            break;
        }
    }
}

就是这个循环

// Apply buffered information
for (std::size_t i = 0; i != buffer.size(); ++i)
{
    walkers[i].randomWalk = 0; // make it dead
    fixed.push_back(walkers[i]); // put it in the fixed/dead vector
    walkers.erase(walkers.begin() + i); // take it out from the main alive vector
}

您在循环遍历 walkers 之前删除了元素,并通过 buffer.size()

对其进行了限制

您是否打算使用 buffer 中的索引?