• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Feb 17th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. template <typename T>
2. Matrix<T> Matrix<T>::operator + (const Matrix<T> &M){
3.     Matrix<T> tmp(m,n,M.x);
4.     for(int i=0;i<m;i++)
5.         for(int j=0;j<n;j++)
6.             tmp.Mat[i][j]+= Mat[i][j]+ M.Mat[i][j];
7.     return tmp;
8. }
9.
10. #include <iostream>
11. #include <vector>
12.
13. template <typename T>
14. class Matrix {
15. private:
16.     unsigned int m; unsigned int n;
17.     std::vector<T> x;
18.     std::vector<T> y;
19.     std::vector<std::vector<int>> Mat;
20.
21.
22. public:
23.     Matrix (unsigned int m, unsigned int n, std::vector<T> x);
24.     Matrix (const Matrix<T> &M); //= default;
25.    // Matrix ();
26.     Matrix<T> operator = (const Matrix<T> &M);      // Assignment
27.     Matrix<T> operator + (const Matrix<T> &M);      // Addition
28.     Matrix<T> operator - (const Matrix<T> &M);      // Subtraction
29.     Matrix<T> operator * (const T &scalar);          // Scalar Multiplication
30.     Matrix<T> operator * (const Matrix<T> &M);      // Matrix Multiplication
31.
32.     friend std::ostream& operator << (std::ostream& os, const Matrix<T> &M){
33.
34.     for (int i = 0; i< M.m; i++){
35.         for (int j = 0; j< M.n; j++){
36.             os << M.Mat[i][j] << ' ';
37.         }
38.         os << 'n';
39.     }
40.     os << 'n' ;
41.     return os;
42.     }
43. };
44.
45. template <typename T>
46. Matrix<T>::Matrix (unsigned int m, unsigned int n, std::vector<T> x){ //constructor
47. this -> m = m;
48. this -> n = n;
49. this -> x = x;
50.
51. int index = 0;
52. Mat.resize(m);
53. for (unsigned int i = 0; i < Mat.size(); i++) {
54.     Mat[i].resize(n);
55. }
56. for (unsigned int i = 0; i<m; i++){
57.     for (unsigned int j = 0; j<n; j++){
58.         Mat[i][j] = x[index];
59.         index++;
60.     }
61. }
62. }
63.
64. template<typename T>
65. Matrix<T>::Matrix(const Matrix &M) //copy constructor
66. :
67. m(M.m),
68. n(M.n),
69. Mat(M.Mat)
70. {}
71.
72. int main(){
73. std::vector<int> x = {1,2,3,4};
74. std::vector<int> y = {5,6,7,8};
75. std::vector<int> z = {9,10,11,12};
76.
77. Matrix<int> A{2,2,x};
78. Matrix<int> B{2,2,y};
79. Matrix<int> C{2,2,z};
80.
81. C = B;
82.
83.
84. std::cout << "An" << A;
85. std::cout << "Bn" << B;
86. std::cout << "Cn" << C;
87.
88. Matrix<int> E(A + B);
89. std::cout << "En" << E;
90. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top