使用递归模板动态分配的多维数组

Dynamically allocated multidimensional array using recursive templates

本文关键字:数组 动态分配 递归      更新时间:2023-10-16

为了从MATLAB程序中读取和存储一些结果,我需要使用多达6维的矩阵。而不是做一些类似的事情:

typedef std::vector<double>  Row;
typedef std::vector<Row>     Matrix2;
typedef std::vector<Matrix2> Matrix3;
typedef std::vector<Matrix3> Matrix4;
typedef std::vector<Matrix4> Matrix5;
typedef std::vector<Matrix5> Matrix6;

我决定使用模板,到目前为止我拥有的是:

template <class T, int N>
class Matrix {
public:
typedef typename Matrix<T, N - 1>::type MatrixOneDimLower;
typedef std::vector<MatrixOneDimLower> type;
type _data;
template <unsigned int dn, typename ...NT>
Matrix(unsigned int dn, NT ...drest) : _data(dn, MatrixOneDimLower(drest)) {}
MatrixOneDimLower& operator[](unsigned int index)
{
return _data[index];
}
};
template <class T>
class Matrix<T, 1> {
public:
typedef std::vector<T> type;
type _data;
Matrix(unsigned int d0) : _data(d0, T(0.0)) {}
T& operator[](unsigned int index)
{
return _data[index];
}
};

不幸的是,我不太擅长可变模板和递归模板,这不起作用。例如,如果我尝试将其用作:

Matrix<double, 4> temp(n,  dim[2], dim[1], dim[0]);

我收到这个编译时错误(Visual Studio 2017(:

error C2661: 'Matrix<double,4>::Matrix': no overloaded function takes 4 arguments

如果你能告诉我我做错了什么,我将不胜感激。

template<class T, std::size_t I>
struct MatrixView {
MatrixView<T, I-1> operator[](std::size_t i) {
return {ptr + i* *strides, strides+1};
}
MatrixView( T* p, std::size_t const* stride ):ptr(p), strides(stride) {}
private:
T* ptr = 0;
std::size_t const* strides = 0;
};
template<class T>
struct MatrixView<T, 1> {
T& operator[](std::size_t i) {
return ptr[i];
}
MatrixView( T* p, std::size_t const* stride ):ptr(p) {}
private:
T* ptr = 0;
};
template<class T, std::size_t N>
struct Matrix {
Matrix( std::array<std::size_t, N> sizes ) {
std::size_t accumulated = 1;
for (std::size_t i = 1; i < sizes.size(); ++i) {
accumulated *= sizes[N-i];
strides[N-i] = accumulated;
}
storage.resize( strides[0] * sizes[0] );
}
MatrixView<T, N> get() { return {storage.data(), strides.data()}; }
MatrixView<T const, N> get() const { return {storage.data(), strides.data()}; }
private:
std::vector<T> storage;
std::array<std::size_t, N-1> strides;
};

这需要执行CCD_ 1以创建具有6个维度的矩阵。

要访问它,您需要执行m.get()[3][0][0][0][0][0] = 4

你可以去掉.get(),但只要你想支持一阶张量,它就有点烦人。

数据是连续存储的。