gpt4 book ai didi

c++ - 用索引直接访问替换循环(和其中的条件)

转载 作者:行者123 更新时间:2023-11-27 23:39:34 25 4
gpt4 key购买 nike

我有一个 for 循环,其中有一个条件,用于在 index 处查找缓冲区的值:

// uint index = ...
// const float *bufferPtr = ...
// uint stride = ...
// uint vertexCount = ...

for (uint i = 0; i < vertexCount; i++) {
float xVal = *bufferPtr++;
float yVal = *bufferPtr++;
float zVal = *bufferPtr++;
bufferPtr += stride;
if (i == index) {
qDebug() << "Vertex coord: " << xVal << " , " << yVal << " , " << zVal;
}
}

我尝试用索引直接访问来替换 for 循环(和其中的条件):

float xVal = *(bufferPtr + index * stride + 0);
float yVal = *(bufferPtr + index * stride + 1);
float zVal = *(bufferPtr + index * stride + 2);
qDebug() << "Vertex coord without loop: " << xVal << " , " << yVal << " , " << zVal;

但是输出日志给我不同的结果:

Vertex coord:  14.574  ,  -8.236  ,  7.644
Vertex coord without loop: 20.67 , -19.098 , 18.536
Vertex coord: 14.552 , -8.024 , 7.842
Vertex coord without loop: -0.361096 , 0.109164 , 0.926117
Vertex coord: 14.722 , -8.18 , 7.842
Vertex coord without loop: 20.648 , -19.052 , 18.522

我不明白为什么结果不同:(


修复

正如@LanceDeGate 回答所建议的,通过在循环之前将stride 减少3 解决了这个问题:


stride = stride - 3; // Three floats per vertex

for (uint i = 0; i < vertexCount; i++) {
float xVal = *bufferPtr++;
float yVal = *bufferPtr++;
float zVal = *bufferPtr++;
bufferPtr += stride;
if (i == index) {
qDebug() << "Vertex coord: " << xVal << " , " << yVal << " , " << zVal;
}
}

现在日志是一样的:

Vertex coord:  -0.522632  ,  -0.803892  ,  -9.02102
Vertex coord without loop: -0.522632 , -0.803892 , -9.02102
Vertex coord: -0.39095 , -2.04955 , -8.91668
Vertex coord without loop: -0.39095 , -2.04955 , -8.91668
Vertex coord: -0.259928 , -0.804899 , -9.03231
Vertex coord without loop: -0.259928 , -0.804899 , -9.03231

最佳答案

可能是因为在三个“bufferPtr++”之后,整个stride被添加到bufferPtr。

也许这就是你的意思:

float xVal = *bufferPtr;
float yVal = *(bufferPtr+1);
float zVal = *(bufferPtr+2);
bufferPtr += stride;

float xVal = *bufferPtr++;
float yVal = *bufferPtr++;
float zVal = *bufferPtr++;
bufferPtr += (stride-3);

关于c++ - 用索引直接访问替换循环(和其中的条件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56413239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com