尝试push_back()结构会导致2D向量中的信息不正确
Attempting to push_back() a struct results in incorrect information in 2D vector
我有一个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);
}
}
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 如何在C++或OpenCV子矩阵中的2D子向量上使用OpenACC?
- 哪个更快:在 1d 向量中按字符串搜索还是在 2d 向量中按向量搜索?
- 分配具有 2D 向量大小的变量的内存
- 根据组件 1、2(和 3)对空间 (2D/3D) 向量进行排序
- 在统一内存 CUDA C/C++ 中分配 2D 向量
- 索引 2D 向量时'Reference to type const..'编译错误
- 查找 2D 向量的位置,该向量是类C++的一个元素
- 如何在 C++ 中的函数中传递 2D 向量的子向量
- 为 2D 向量类创建标量乘法运算符
- 无法使用push_back将整数插入1D/2D向量
- 如何将列附加到现代C 中的2D向量
- 如何声明和初始化一个特定尺寸向量的2D数组
- 如何计算 2D 数组中每行的总和并放置在向量中
- 在不使用递归的情况下求解所有 2D 字符串向量组合?(C++)
- 在类中创建向量(2D 数组)的向量 - Error:C++ 需要所有声明的类型说明符
- 在C++中使用向量的向量(2D 向量)表示邻接列表
- 将向量(2D数组)的向量重置为零