Advertisement
sdfDFASDFASDF

Untitled

May 20th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.95 KB | None | 0 0
  1. #pragma once
  2. #include <string>
  3.  
  4. template <typename T>
  5. class Matrix
  6. {
  7. public:
  8. // Конструкторы ---------------------------------
  9. Matrix(); // Конструктор по умолчанию -----------
  10. Matrix(T** arr_, const int& i, const int& j); // Конструктор инициализатор
  11. Matrix(T* arr_, const int& i, const int& j); // Конструктор инициализатор
  12. Matrix(const int& i, const int& j); // Конструктор инициализатор (создает матрицу заданного размера заполненную 0)
  13. Matrix(const Matrix<T>& copy); // Конструктор копирования
  14.  
  15. // Методы класса --------------------------------
  16. // Получение количества строк
  17. int getN() const
  18. {
  19. return n;
  20. }
  21.  
  22. // Получение колисчества столбцов
  23. int getM() const
  24. {
  25. return m;
  26. }
  27.  
  28. // Поиск максимума в массиве того же типа
  29. static T Max(T** arr_, const int& n_, const int& m_);
  30.  
  31. // Поиск максимума в матрице
  32. T Max() const;
  33.  
  34. // Получение копии матрицы в виде массива
  35. T** getCopy();
  36.  
  37. // Заполнение матрицы заданным значением
  38. void Fill(const T& a);
  39.  
  40. // Получение подматрицы
  41. Matrix<T> getPodmatrix(const int& poz_n_, const int& poz_m_, const int& n_, const int& m_) const;
  42.  
  43. // Перегрузки операторов ------------------------
  44. Matrix<T>& operator= (const Matrix<T>& copy); // Оператор присваивания
  45. Matrix<T> operator+ (const Matrix<T>& mat) const; // Оператор суммы
  46. Matrix<T> operator* (const Matrix<T>& mat) const; // Оператор произведения
  47. Matrix<T> operator* (const int k) const; // Оператор произведения на число
  48. template <typename T1> friend Matrix<T1> operator* (const int k, const Matrix<T1>& mat); // Оператор произведения на число
  49. template <typename T1> friend std::ostream& operator<< (std::ostream& out, const Matrix<T1>& mat); // Оператор вывод матрицы в поток
  50. template <typename T1> friend std::istream& operator>> (std::istream& out, Matrix<T1>& mat); // Оператор чтение матрицы из потока
  51. std::shared_ptr<T[]> operator[] (int index); // Оператор индексации
  52. const std::shared_ptr<T[]> operator[] (int index) const; // Оператор индексации константы
  53. bool operator==(const Matrix<T>& mat) const; // Оператор сравнения матриц
  54.  
  55.  
  56. // Деструктор -----------------------------------
  57. virtual ~Matrix();
  58.  
  59. // Класс исключений ----------------------------
  60. class MatrixExeption : public std::runtime_error
  61. {
  62. public:
  63. MatrixExeption(std::string s) : std::runtime_error(s) {}
  64. ~MatrixExeption() {}
  65. };
  66. protected:
  67.  
  68. // Поля класса ----------------------------------
  69. int n, // Количество строк в матрице
  70. m; // Количество столбцов с матрице
  71. std::shared_ptr < std::shared_ptr<T []>[] > arr; // Матрица
  72.  
  73. // Скрытые матоды класса ------------------------
  74. void initMat(); // Выделение памяти для матрицы
  75. void isInRange(int index) const; // Проверяет, находится ли индекс в допустимых границах
  76. };
  77.  
  78.  
  79. // Реализация ---------------------------------------
  80. template<typename T>
  81. Matrix<T>::Matrix() : n(0), m(0)
  82. {
  83. arr = nullptr;
  84. }
  85.  
  86. template<typename T>
  87. Matrix<T>::Matrix(T** arr_, const int& i, const int& j) : n(i), m(j)
  88. {
  89. if ((n < 0) || (m < 0)) {
  90. throw Matrix::MatrixExeption("Неверный размер матрицы!");
  91. }
  92. initMat();
  93. for (int i = 0; i < n; i++) {
  94. for (int j = 0; j < m; j++) {
  95. arr[i][j] = arr_[i][j];
  96. }
  97. }
  98. }
  99.  
  100. template<typename T>
  101. Matrix<T>::Matrix(T* arr_, const int& i, const int& j) : n(i), m(j)
  102. {
  103. if ((n < 0) || (m < 0)) {
  104. throw Matrix::MatrixExeption("Неверный размер матрицы!");
  105. }
  106. initMat();
  107. for (int i = 0; i < n; i++) {
  108. for (int j = 0; j < m; j++) {
  109. arr[i][j] = arr_[i*m + j];
  110. }
  111. }
  112. }
  113.  
  114. template<typename T>
  115. Matrix<T>::Matrix(const int& i, const int& j) : n(i), m(j)
  116. {
  117. if ((n < 0) || (m < 0)) {
  118. throw Matrix::MatrixExeption("Неверный размер матрицы!");
  119. }
  120. initMat();
  121. for (int i = 0; i < n; i++) {
  122. for (int j = 0; j < m; j++) {
  123. arr[i][j] = T();
  124. }
  125. }
  126. }
  127.  
  128. template<typename T>
  129. Matrix<T>::Matrix(const Matrix<T> & copy) : n(copy.n), m(copy.m)
  130. {
  131. initMat();
  132. for (int i = 0; i < n; i++) {
  133. for (int j = 0; j < m; j++) {
  134. arr[i][j] = copy.arr[i][j];
  135. }
  136. }
  137. }
  138.  
  139. template<typename T>
  140. Matrix<T> Matrix<T>::getPodmatrix(const int& poz_n_, const int& poz_m_, const int& n_, const int& m_) const {
  141. if ((poz_n_ < 0) || (poz_m_ < 0)||(poz_n_ >= n)||(poz_m_ >= m)) {
  142. throw Matrix::MatrixExeption("Неверная позиция верхнего левого элемента подматрицы!");
  143. }
  144. if (((poz_n_ + n_) > n) || ((poz_m_ + m_) > m)) {
  145. throw Matrix::MatrixExeption("Подматрица выходит за границы матрицы!");
  146. }
  147.  
  148. Matrix<T> rez(n_, m_);
  149.  
  150. for (int i = 0; i < n_; i++) {
  151. for (int j = 0; j < m_; j++) {
  152. rez[i][j] = arr[poz_n_ + i][poz_m_ + j];
  153. }
  154. }
  155. return rez;
  156. }
  157.  
  158. template<typename T>
  159. T Matrix<T>::Max(T** arr_, const int& n_, const int& m_) {
  160. T max = arr_[0][0];
  161. for (int i = 0; i < n_; i++) {
  162. for (int j = 0; j < m_; j++) {
  163. if (arr_[i][j] > max) {
  164. max = arr_[i][j];
  165. }
  166. }
  167. }
  168. return max;
  169. }
  170.  
  171. template<typename T>
  172. T Matrix<T>::Max() const {
  173. T max = arr[0][0];
  174. for (int i = 0; i < n; i++) {
  175. for (int j = 0; j < m; j++) {
  176. if (arr[i][j] > max) {
  177. max = arr[i][j];
  178. }
  179. }
  180. }
  181. return max;
  182. }
  183.  
  184. template<typename T>
  185. T** Matrix<T>::getCopy()
  186. {
  187. T** copy;
  188. copy = new T*[n];
  189. for (int i = 0; i < n; i++) {
  190. copy[i] = new T[m];
  191. }
  192. for (int i = 0; i < n; i++) {
  193. for (int j = 0; j < m; j++) {
  194. copy[i][j] = arr[i][j];
  195. }
  196. }
  197. return copy;
  198. }
  199.  
  200. template<typename T>
  201. void Matrix<T>::Fill(const T& a) {
  202. for (int i = 0; i < n; i++) {
  203. for (int j = 0; j < m; j++) {
  204. arr[i][j] = a;
  205. }
  206. }
  207. }
  208.  
  209. template<typename T>
  210. Matrix<T>& Matrix<T>::operator=(const Matrix<T> & copy)
  211. {
  212. if (this == &copy) {
  213. return *this;
  214. }
  215. if ((copy.n > n) || (copy.m > m)) {
  216. for (int i = 0; i < n; i++) {
  217. arr[i].reset();
  218. }
  219. arr.reset();
  220. n = copy.n;
  221. m = copy.m;
  222. initMat();
  223. }
  224. else {
  225. n = copy.n;
  226. m = copy.m;
  227. }
  228.  
  229. for (int i = 0; i < n; i++) {
  230. for (int j = 0; j < m; j++) {
  231. arr[i][j] = copy.arr[i][j];
  232. }
  233. }
  234. return *this;
  235. }
  236.  
  237. template<typename T>
  238. Matrix<T> Matrix<T>::operator+(const Matrix<T> & mat) const
  239. {
  240. Matrix<T> tmp(*this);
  241. if ((n != mat.n) || (m != mat.m)) {
  242. throw MatrixExeption("Невозможно выполнить сложение матриц разного размера");
  243. }
  244. for (int i = 0; i < n; i++) {
  245. for (int j = 0; j < m; j++) {
  246. tmp[i][j] += mat.arr[i][j];
  247. }
  248. }
  249. return tmp;
  250. }
  251.  
  252. template<typename T>
  253. Matrix<T> Matrix<T>::operator*(const Matrix<T> & mat) const
  254. {
  255. if (m != mat.n) {
  256. throw MatrixExeption("Невозможно выполнить умножение матриц с несовпадающим количеством столбцов в первой и строк во второй");
  257. }
  258. Matrix<T> tmp(n, mat.m);
  259. for (int i = 0; i < n; i++) {
  260. for (int j = 0; j < mat.m; j++) {
  261. for (int o = 0; o < m; o++) {
  262. tmp[i][j] += (arr[i][o] * mat.arr[o][j]);
  263. }
  264. }
  265. }
  266. return tmp;
  267. }
  268.  
  269. template<typename T>
  270. Matrix<T> Matrix<T>::operator*(const int k) const
  271. {
  272. Matrix<T> tmp(*this);
  273. for (int i = 0; i < n; i++) {
  274. for (int j = 0; j < m; j++) {
  275. tmp[i][j] *= k;
  276. }
  277. }
  278. return tmp;
  279. }
  280.  
  281. template<typename T>
  282. std::shared_ptr<T[]> Matrix<T>::operator[](int index)
  283. {
  284. isInRange(index);
  285. return arr[index];
  286. }
  287.  
  288. template<typename T>
  289. const std::shared_ptr<T[]> Matrix<T>::operator[](int index) const
  290. {
  291. isInRange(index);
  292. return arr[index];
  293. }
  294.  
  295. template<typename T>
  296. bool Matrix<T>::operator==(const Matrix<T> & mat) const
  297. {
  298. if ((n != mat.n) || (m != mat.m)) {
  299. return false;
  300. }
  301. for (int i = 0; i < n; i++) {
  302. for (int j = 0; j < m; j++) {
  303. if (arr[i][j] != mat.arr[i][j]) {
  304. return false;
  305. }
  306. }
  307. }
  308. return true;
  309. }
  310.  
  311. template<typename T>
  312. Matrix<T>::~Matrix()
  313. {
  314. for (int i = 0; i < n; i++) {
  315. arr[i].reset();
  316. arr[i] = nullptr;
  317. }
  318. arr.reset();
  319. arr = nullptr;
  320. }
  321.  
  322. template<typename T>
  323. void Matrix<T>::initMat()
  324. {
  325. arr.reset(new std::shared_ptr<T []>[n]);
  326. for (int i = 0; i < n; i++) {
  327. arr[i].reset(new T[m]);
  328. }
  329. }
  330.  
  331. template<typename T>
  332. void Matrix<T>::isInRange(int index) const
  333. {
  334. if ((index > n) || (index < 0)) {
  335. throw MatrixExeption("Индекс выходит за размер матрицы!");
  336. }
  337. }
  338.  
  339. template<typename T>
  340. Matrix<T> operator*(const int k, const Matrix<T> & mat)
  341. {
  342. Matrix<T> tmp(mat);
  343. for (int i = 0; i < mat.n; i++) {
  344. for (int j = 0; j < mat.m; j++) {
  345. tmp[i][j] *= k;
  346. }
  347. }
  348. return tmp;
  349. }
  350.  
  351. template<typename T>
  352. std::ostream& operator<<(std::ostream& out, const Matrix<T> & mat)
  353. {
  354. out << mat.n << ' ' << mat.m << std::endl; // Для совместимости с вводом из файла
  355.  
  356. for (int i = 0; i < mat.n; i++) {
  357. for (int j = 0; j < mat.m; j++) {
  358. out << mat.arr[i][j] << ' ';
  359. }
  360. out << std::endl;
  361. }
  362. return out;
  363. }
  364.  
  365. template<typename T>
  366. std::istream& operator>>(std::istream & in, Matrix<T> & mat)
  367. {
  368. in >> mat.n;
  369. in >> mat.m;
  370. if ((mat.n < 0) || (mat.m < 0)) {
  371. throw Matrix<T>::MatrixExeption("Неверный размер матрицы!");
  372. }
  373. mat.initMat();
  374. for (int i = 0; i < mat.n; i++) {
  375. for (int j = 0; j < mat.m; j++) {
  376. in >> mat.arr[i][j];
  377. }
  378. }
  379. return in;
  380. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement