首页 > 解决方案 > 使用向量的向量的 N 维矩阵类

问题描述

我正在尝试实现一个自定义类,该类使用向量的向量处理 n 维矩阵,概括 1d、2d 和 3d 定义:

using mat1dd = std::vector<double>;
using mat2dd = std::vector<mat1dd>;
using mat3dd = std::vector<mat2dd>;

这是我实现这个类的尝试。

template <std::size_t N_DIM, typename T>
class matnd {
    std::vector<matnd<N_DIM - 1, T>> mat;
    ...
}

我的意图是,例如,

matnd<3, double> mat;

创建一个双精度的 3 维矩阵。

上面的递归定义显然失败了,因为它没有基本情况,所以N_DIM只是无限期地减少(直到编译器停止)。我怎样才能以不遇到这个问题的方式实现这个类?

标签: c++matrixlinear-algebran-dimensional

解决方案


使用包含类型定义的模板结构将其专门用于n = 1

template<size_t n, typename T>
struct matnd_helper
{
    using type = std::vector<typename matnd_helper<n - 1, T>::type>;
};

template<typename T>
struct matnd_helper<1, T>
{
    using type = std::vector<T>;
};

template<size_t n, typename T>
using matnd = typename matnd_helper<n, T>::type;

using mat1dd = matnd<1, double>;
using mat2dd = matnd<2, double>;
using mat3dd = matnd<3, double>;



推荐阅读