C++ -- 实现矩阵类
来源:互联网 发布:焊接模拟软件 编辑:程序博客网 时间:2024/06/05 12:49
#ifndef MATRIX_H#define MATRIX_H#include <iostream>using namespace std;template <typename E>class Matrix{public: int rows,cols,length; Matrix(int _m,int _n); Matrix(const Matrix<E> &M) ; ~Matrix(); Matrix<E> & operator+(Matrix<E> &M); Matrix<E> & operator-(Matrix<E> &M); Matrix<E> & operator=(const Matrix<E> &M); Matrix<E> & T(); E& operator()(int i,int j) { if ( (i>=0 && i<rows) &&(j>=0 && j<cols ) ){ return basePtr[i*cols+j]; }else { cout<<"subscript over bounded!"<<endl; exit(0); } }private: E* basePtr;};/* 模板类的声明与定义不能分开为两个文件,只有部分编译器支持声明与实现分开。 */template <typename E>Matrix<E>::Matrix(int _m,int _n){ rows=_m;cols=_n; if( !(rows==0 || cols==0 )){ length=rows*cols; basePtr =new E[length]; } else cout<<"Error!"<<endl;}template <typename E>Matrix<E>::~Matrix(){ if(basePtr) delete[] basePtr;}template <typename E>Matrix<E>& Matrix<E>:: operator+(Matrix<E> &M){ if( M.rows == rows && M.cols==cols){ Matrix<E> * res= new Matrix<E>(rows,cols); #pragma omp parallel for for(int i=0;i<length;++i){ res->basePtr[i]=basePtr[i]+M.basePtr[i]; } return *res; }else { cout<< "Matrix in operator+ are in different size"<<endl; return *this; }}template <typename E>Matrix<E> & Matrix<E> :: operator-(Matrix<E> &M){ if( M.rows == rows && M.cols==cols){ Matrix<E> * res= new Matrix<E>(rows,cols); #pragma omp parallel for for(int i=0;i<length;++i){ res->basePtr[i]=basePtr[i]-M.basePtr[i]; } return *res; }else { cout<< "Matrix in operator+ are in different size"<<endl; exit(0); }}template <typename E>Matrix<E> :: Matrix(const Matrix<E> &M){ rows=M.rows; cols=M.cols; length = M.length; basePtr =new E[length]; // #pragma omp parallel for for(int i=0;i<length;++i) { basePtr[i] =M.basePtr[i]; }}/** * */template<typename E>Matrix<E> & Matrix<E> :: operator=(const Matrix<E> &M){ if(this==&M) return *this; if(basePtr) delete[] basePtr; rows=M.rows; cols=M.cols; length=M.length; basePtr =new E[length]; for(int i=0;i<length;++i) basePtr[i]=M.basePtr[i]; return *this;}template<typename E>Matrix<E> & Matrix<E> :: T(){ Matrix<E> *result= new Matrix<E>(cols,rows); result->length =length; int i,j; for(int k=0;k<length;++k) { i=k/cols; j=k-i*cols; result->basePtr[j*rows+i] =basePtr[k]; } return *result;}#endif // MATRIX_H
阅读全文
0 0
- 螺旋矩阵(c实现)
- C语言实现矩阵相乘
- 矩阵求逆用C语言实现
- 螺旋矩阵的C实现
- 螺旋矩阵C语言实现
- 矩阵乘法C语言实现
- C语言实现矩阵相乘
- C堆内矩阵实现
- 螺旋矩阵(c语言实现)
- C实现矩阵加减乘除运算
- C语言实现矩阵乘法
- C实现矩阵加减乘除运算
- C语言实现矩阵乘法
- C语言实现矩阵相乘
- 矩阵相乘 C语言实现
- C语言实现蛇形矩阵
- 【C++】模版矩阵类
- OpenGL矩阵类(C++)
- 浅谈 最大子矩阵
- 改进版python实现的归并排序
- DOM
- npm太慢, 淘宝npm镜像使用方法
- 什么是回程网络(backhual telecommunications )
- C++ -- 实现矩阵类
- Spring 4.X 使用@AspectJ和Schema 报错
- 【前端】js常用函数封装
- win32创建对话框的方法(1)
- Ubuntu下onos安装笔记
- SPSS Statistics(spss25.0)25.0中文免费版下载
- 学习笔记——12306 手动登录解析(1)
- 栈和队列
- 图形打印