gpt4 book ai didi

c++ - 尝试 push_back() 结构会导致 2D vector 中的信息不正确

转载 作者:行者123 更新时间:2023-11-28 06:40:41 24 4
gpt4 key购买 nike

我有一个 2D vector ,我试图用坐标填充它。为了我自己的缘故,我已经为坐标定义了一个结构,但出于某种原因,push_back() 函数没有将正确的 y 坐标推到 vector 上,而是只推第一个。

这是有问题的代码:其余代码对这个片段来说不太重要。

struct coor2d {
float x;
float y;
};

// Inside a function
int row = 5;
int col = 5;
float r_wide = 1.0/float(row);
float r_high = 1.0/float(col);

vector<vector<coor2d> > grid;
vector<coor2d> column;
for(int cr = 0; cr < row; cr++) {
for(int cc = 0; cr < col; cc++) {
coor2d temp;
temp.x = (float(cc) * r_wide) + (r_wide/2.0);
temp.y = ((float(cr) * r_high) + (r_high/2.0) * -1.0);
// Here the temp.y value is correct
column.push_back(temp);
// Here the temp.y value is incorrect
}
grid.push_back(column);
}

其余代码取决于此是否正常工作。我假设我正在失去精度或在这里错误地调用了一些东西。我知道我可以为 coor2d 创建一个构造函数,但我认为这不能解决这个问题;但是,我可能是错的。

问题表现的一个例子:

一旦通过 for(cr < row) 循环的第一次迭代,内部 for(cc < col) 循环输出正确的 x 坐标,但在 column.push_back(temp) 完成后,y 坐标就好像 cr 仍然是 0.0f 而不是 1.0f,将 -0.1f 而不是正确的 -0.3f 输出到 vector 中。这发生在 cr 的任何值上。

任何人都可以阐明这个问题吗?感谢您的帮助!

最佳答案

正如@Erik 所指出的,您打错了字。这:

for(int cc = 0; cr < col; cc++) {

应该是这样的:

for(int cc = 0; cc < col; cc++) {

此外,我认为您可能希望在外部 for 循环的每次传递时“重置”您的 column vector 。我认为简单的方法就是移动它:

vector<vector<coor2d> > grid;
for(int cr = 0; cr < row; cr++) {
vector<coor2d> column; // move the column vector to here
for(int cc = 0; cr < col; cc++) {

如果您不这样做, vector 只会累积您向其推送的所有值。

通过这些更改,我从这个测试程序中得到了我认为“正常”的输出:

#include <iostream>
#include <vector>

struct coor2d {
float x;
float y;
};

int main(){
// Inside a function
int row = 5;
int col = 5;
float r_wide = 1.0/float(row);
float r_high = 1.0/float(col);

for(int cr = 0; cr < row; cr++) {
std::vector<coor2d> column;
for(int cc = 0; cc < col; cc++) {
coor2d temp;
temp.x = (float(cc) * r_wide) + (r_wide/2.0);
temp.y = ((float(cr) * r_high) + (r_high/2.0) * -1.0);
// Here the temp.y value is correct
column.push_back(temp);
// Here the temp.y value is incorrect
std::cout << "temp.x: " << temp.x << " temp.y: " << temp.y << std::endl;
std::cout << "vec.x: " << column[cc].x << " vec.y: " << column[cc].y << std::endl;
}
grid.push_back(column);
}
}

关于c++ - 尝试 push_back() 结构会导致 2D vector 中的信息不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26029884/

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