在c ++中一个类有可能有一个成员是一个多维数组,其维度和范围在运行时之前是未知的? [英] Is it possible in c++ for a class to have a member which is a multidimensional array whose dimensions and extents are not known until runtime?
问题描述
我最初问使用嵌套std: :数组创建一个多维数组,直到运行时才知道维度或范围,但这有尝试使用std :: array完成它的XY问题。
The questions One-line initialiser for Boost.MultiArray and How do I make a multidimensional array of undetermined size a member of a class in c++? and their answers give some helpful information how to use Boost::MultiArray to avoid needing to know the extents of the dimensions at runtime, but fail to demonstrate how to have a class member that can store an array (created at runtime) whose dimensions and extents are not known until runtime.
推荐答案
只要避免使用多维数组:
Just avoid multidimensional arrays:
template<typename T>
class Matrix
{
public:
Matrix(unsigned m, unsigned n)
: n(n), data(m * n)
{}
T& operator ()(unsigned i, unsigned j) {
return data[ i * n + j ];
}
private:
unsigned n;
std::vector<T> data;
};
int main()
{
Matrix<int> m(3, 5);
m(0, 0) = 0;
// ...
return 0;
}
3D存取(在正确的3D矩阵中) >
A 3D access (in a proper 3D matrix) would be:
T& operator ()(unsigned i, unsigned j, unsigned k) {
// Please optimize this (See @Alexandre C)
return data[ i*m*n + j*n + k ];
}
获取任意维度和范围将遵循该方案并添加重载范围信息)和/或利用可变参数模板。
Getting arbitrary dimensions and extent would follow the scheme and add overloads (and dimensional/extent information) and/or take advantage of variadic templates.
有很多维度可以在上面避免(即使在C ++ 11中),并且用std :: vector替换参数。例如:运算符(std :: vector indices)。
每个维度(除了最后一个)将有一个存储在向量n(作为上面2D示例中的第一个维度)的扩展。
Having a lot of dimensions you may avoid above (even in C++11) and replace the arguments by a std::vector. Eg: T& operator(std::vector indices). Each dimension (besides the last) would have an extend stored in a vector n (as the first dimension in the 2D example above).
这篇关于在c ++中一个类有可能有一个成员是一个多维数组,其维度和范围在运行时之前是未知的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!