Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- template <typename T>
- struct Matrix
- {
- int nDim_n = 0, nDim_m = 0;
- std::vector<std::vector<T>> MAT;
- void ReadMatrix(int);
- void ReserveMatrix();
- void ReadValues();
- void Print();
- Matrix MatMultiplyMat(Matrix rhs, bool print);
- bool checkCompatibility(Matrix rhs);
- };
- int main()
- {
- Matrix<int> M1, M2;
- M1.ReadMatrix(1);
- M2.ReadMatrix(2);
- std::cout << "M1 M2 \n";
- M1.MatMultiplyMat(M2, true);
- std::cout << "M2 M1 \n";
- M2.MatMultiplyMat(M1, true);
- }
- template <typename T>
- void Matrix<T>::ReadMatrix(int nCountOfMatrix)
- {
- std::cout << "Number of lines of Matrix " << nCountOfMatrix << "?\n";
- std::cin >> nDim_n;
- std::cout << "Number of columns of Matrix " << nCountOfMatrix << "?\n";
- std::cin >> nDim_m;
- ReserveMatrix();
- ReadValues();
- }
- template <typename T>
- void Matrix<T>::ReserveMatrix()
- {
- MAT.resize(nDim_n);
- for (auto& v : MAT)
- v.resize(nDim_m);
- }
- template <typename T>
- void Matrix<T>::ReadValues()
- {
- for (auto& v : MAT)
- for (auto& x : v)
- std::cin >> x;
- }
- template <typename T>
- bool Matrix<T>::checkCompatibility(Matrix<T> rhs)
- {
- return (nDim_m == rhs.nDim_n);
- }
- template <typename T>
- Matrix<T> Matrix<T>::MatMultiplyMat(Matrix<T> rhs, bool print)
- {
- Matrix<T> result;
- if (checkCompatibility(rhs))
- {
- result.nDim_n = nDim_n;
- result.nDim_m = rhs.nDim_m;
- result.ReserveMatrix();
- for (int i = 0; i < nDim_n; ++i)
- {
- for (int j = 0; j < rhs.nDim_m; ++j)
- {
- T value = 0;
- for(int k = 0; k < nDim_m; ++k)
- value += MAT[i][k] * rhs.MAT[k][j];
- result.MAT[i][j] = value;
- }
- }
- if (print)
- result.Print();
- }
- else
- {
- std::cout << "Cannot multiply these two!";
- }
- return result;
- }
- template <typename T>
- void Matrix<T>::Print()
- {
- for (auto& v : MAT)
- {
- for (auto& x : v)
- std::cout << x << " ";
- std::cout << "\n";
- }
- std::cout << "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement