使用while循环时出现问题

An issue when looping with while

本文关键字:问题 while 循环 使用      更新时间:2023-10-16

我有一个向量QVector<float> dist;,其中我为所有维度保持欧几里得距离。我保留以下尺寸:

QHash<int, QVector<float> > hash; 

其中int用于密钥,并且这些值再次保存在QVector<float>中。当我尝试填充dist时,代码如下:

for(int i = 0; i < t; i++)
    {
        for(int j = 1; j < t; j++)
        {
            while( j <= i)
                j++;
            dist.push_back(qPow((a[i] - hash[i].at(point)), 2) + qPow((a[j] - hash[j].at(point)), 2));
            qDebug() << "Euclidean distance for Dim" << i << "and Dim" << j << " = " << dist[i];
        }
    }

循环按预期计算所有内容,但在之后因内存错误而崩溃

QVector::中的ASSERT失败,位于"索引超出范围"。。。

当我删除while循环(计算将出错)时,应用程序不再崩溃。

由于i<t和j可能等于i+1,在访问a[j]时可能产生超出范围的误差。也就是说,有时j=t,所以你试图访问a[t]。它看起来不正确。

也许放是正确的

while( j < i)

而不是

while( j <= i)