如何使用 3 维数据作为类属性?
我已经很长时间没有使用 C++ 了,但我有一个使用 3 维数据的类,但我不知道如何才能完成这项工作。我需要在构造函数中定义尺寸的大小。我在标题中尝试了这个:
class CImage
{
public:
float values[][][];
...
}
在构造函数中尝试了这个:
CImage::CImage(int cols, int rows, int depth)
{
values[cols][rows][depth];
}
但这返回错误:“将‘值’声明为多维数组必须具有除第一个维度之外的所有维度的界限”。
在构造函数中使用它也不起作用:
values = new float[cols][rows][depth];
我也尝试使用向量,但没有取得多大成功。标题:
vector<vector<vector<float> > > values;
构造函数中没有任何内容。没有编译器错误,但是当我尝试设置一个值时:
values[c][r][d] = value;
程序崩溃。
看起来很基础,但我就是不明白......
It's been a long time since I worked with C++, but I have a class that uses 3-dimensional data and I can't figure out how I can make this work. I need the sizes of the dimensions to be defined in the constructor. I tried this in the header:
class CImage
{
public:
float values[][][];
...
}
and this in the constructor:
CImage::CImage(int cols, int rows, int depth)
{
values[cols][rows][depth];
}
but this returns the error: "declaration of `values' as multidimensional array must have bounds for all dimensions except the first".
Also using this in the constructor does not work:
values = new float[cols][rows][depth];
I also tried using vector, but without much success. Header:
vector<vector<vector<float> > > values;
Nothing in constructor. No compiler errors, but when I try to set a value:
values[c][r][d] = value;
the program crashes.
It seems so basic, but I just can't figure it out...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
访问该向量时程序崩溃,因为它是空的,即这些索引处没有元素。
解决这个问题的最佳方法是创建一个线性的、一维的向量(甚至是一个数组),并使用一对运算符()来访问它,请参阅C++FAQ Lite 了解详细信息。或者使用 boost::multi_array。
例如:
The program crashes when accessing that vector because it is empty, i.e. there are no elements at those indexes.
The best way to go about this is to make a linear, one-dimensional, vector (or even an array), and access it with a pair of operator()'s, see C++FAQ Lite for details. Or use boost::multi_array.
For example:
只是为了指出为什么 Cubbi 是正确的,这将是 3d 向量的构造函数:
很好,不是吗?
此外,您不能声明浮点值[][][];,因为数组驻留在堆栈上,因此编译器必须在编译时知道该数组的大小(例外:C99变量length 数组,但这不是 C++)。你可以声明一个
float***values;
(在ctor中使用new float[c][r][d];
),但这也很糟糕。Just to poiny out why Cubbi is right, this would be the constructor of the 3d-vector:
Nice, isn't it?
Besides, you cannot declare a
float values[][][];
because arrays reside on the stack, so the compiler has to know at compile time what size that array has (exception to this: C99 variable length arrays, but this would'nt be C++). You could declare afloat*** values;
(usingnew float[c][r][d];
in the ctor), but this is awful, too.