尝试push_back()结构会导致2D向量中的信息不正确

Attempting to push_back() a struct results in incorrect information in 2D vector

本文关键字:向量 2D 不正确 信息 push back 结构 尝试      更新时间:2023-10-16

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

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

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输出到向量中。这发生在cr的任何值上。

有人能阐明这个问题吗?谢谢你的帮助!

正如@Erik所指出的,您有一个拼写错误。此:

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

应该是这样的:

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

此外,我认为您可能希望在每次通过外部for循环时"重置"column向量。我认为简单的方法就是移动它:

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++) {

如果你不这样做,column矢量只会累积你推到它上的所有值

有了这些变化,我从这个测试程序中得到了我认为"理智"的输出:

#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);
  }
}