加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么在创建矩阵类时使用向量是不好的?

发布时间:2020-12-16 10:24:29 所属栏目:百科 来源:网络整理
导读:对于我的矩阵课,我做了: templatetypename T,std::uint32_t Height,std::uint32_t Widthclass Matrix{ private: std::arraystd::arrayT,Width,Height Elements; static_assert(std::is_arithmeticT::value,"Argument T must be of arithmetic type."); publ
对于我的矩阵课,我做了:

template<typename T,std::uint32_t Height,std::uint32_t Width>
class Matrix
{
    private:
        std::array<std::array<T,Width>,Height> Elements;
        static_assert(std::is_arithmetic<T>::value,"Argument T must be of arithmetic type.");

    public:
        Matrix();
        Matrix(T* Data);
        Matrix(T** Data);
        Matrix(T Data[Height][Width]);
        Matrix(const std::array<std::array<T,Height> &Data);

        inline int size() {return Width * Height;}
        inline const int size() const {return Width * Height;}

        inline int width() {return Width;}
        inline const int width() const {return Width;}

        inline int height() {return Height;}
        inline const int height() const {return Height;}

        std::array<T,Width>& operator[](int Index);
        const std::array<T,Width>& operator[](int Index) const;

        Matrix& operator = (const Matrix &M);

        Matrix& operator + (const Matrix &M);

        Matrix& operator - (const Matrix &M);

        Matrix& operator * (const Matrix &M);
};

template<typename T,std::uint32_t Width>
Matrix<T,Height,Width>::Matrix() {std::memset(&Elements,sizeof(T) * Width * Height);}

template<typename T,Width>::Matrix(T* Data) {if (Data) std::memcpy(&Elements,Data,Width>::Matrix(T** Data) {if (Data) std::memcpy(&Elements,&Data[0][0],Width>::Matrix(T Data[Height][Width]) {std::memcpy(&Elements,Width>::Matrix(const std::array<std::array<T,Height> &Data) {std::memcpy(&Elements,std::uint32_t Width>
std::array<T,Width>& Matrix<T,Width>::operator[](int Index) {return Elements[Index];}

template<typename T,std::uint32_t Width>
const std::array<T,Width>::operator[](int Index) const {return Elements[Index];}

因为我在线阅读并且许多评论说不使用向量而是使用数组或使用std :: valarray ..

现在我问的原因是因为我想重写我的矩阵类,所以我不必继续这样做:Matrix< Type,Width,Height>每次..我宁愿在构造函数中执行一次,也不必为每个函数键入它.如上所述.例如,我必须为每个Matrix参数写出每个函数AND的长模板声明.另外我不知道如何删除向量的resize / pushback,这样当用户索引向量时,它们将无法调整大小,因此我使用了数组.

我打算使用一维数组并将其编入索引(I *宽度J),但后来我丢失了[] []运算符.

使用矢量矢量是不是很糟糕?有什么想法来提高我的课程并使其符合RAII标准吗?我不太明白如何使用valarray,上面的内容很难维护.任何想法都表示赞赏.

解决方法

确实,矢量矢量不是最好的方法.假设数据是矩形的(没有锯齿状),矢量矢量方法所做的分配效率很低,更不用说它会阻止一些常见的“重塑”操作(“将我的2×3矩阵视为3×2或6×1而不是复制“).

I was going to use a 1D array and index it doing (I * Width + J) but then I lose my [][] operator.

当然,使用一维矢量.那很棒.然后你可以调整它,重新调整它等,并为许多操作提供接近最佳的性能.你保持RAII.

但你不想失去双下标([x] [y])的能力?好.只需让您的operator []返回一个代理对象(您实现它).代理将拥有自己的operator [],它将在第二个轴上运行.也就是说,第一个[]将返回一个轻量级对象,它足以实现第二个[].

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读