fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <assert.h>
  4.  
  5. #define M 2
  6. #define N 2
  7.  
  8. template <class T>
  9. class MatrixData {
  10. public:
  11. MatrixData(int xx, int yy) : col(xx), row(yy), Value(xx * yy) {}
  12. MatrixData(int xx, int yy, const T& vv) : col(xx), row(yy), Value(xx * yy, vv) {}
  13. friend class Matrix1D;
  14. // proxy配列クラス
  15. class Matrix1D {
  16. public:
  17. Matrix1D(MatrixData<T>& arr, int xx) : array(arr), XIndex(xx) {}
  18. Matrix1D(const MatrixData<T>& arr, int xx) : array(arr), XIndex(xx) {}
  19. T& operator[](int YIndex) {
  20. return array.Value[array.row * XIndex + YIndex];
  21. }
  22. private:
  23. int XIndex;
  24. MatrixData<T>& array;
  25. };
  26. MatrixData<T> operator*(MatrixData<T>& md) {
  27. int i, j, k;
  28. MatrixData<T> tmp(col, md.row);
  29. T sum;
  30.  
  31. // row == md.colの時しか乗算は定義出来ない
  32.  
  33. assert(row == md.col);
  34.  
  35. for (i = 0; i < row; i++)
  36. for (j = 0; j < col; j++) {
  37. sum = 0;
  38. for (k = 0; k < md.col; k++)
  39. sum += (*this)[i][k] * md[k][j];
  40. tmp[i][j] = sum;
  41. }
  42.  
  43. return tmp;
  44. }
  45. Matrix1D operator[](int Xindex) {
  46. return Matrix1D(*this, Xindex);
  47. }
  48. //行列データを画面に表示する
  49. void ShowMatrix()
  50. {
  51. int i, j;
  52.  
  53. for (i = 0; i < row; i++) {
  54. for (j = 0; j < col; j++)
  55. std::cout << (*this)[i][j] << ' ';
  56. std::cout << std::endl;
  57. }
  58. }
  59. //行列の第p行と第q行を入れ替える
  60. void ChangeMatrix(int p, int q)
  61. {
  62. int i;
  63. MatrixData<T> c = *this;
  64.  
  65. for (i = 0; i < col; i++) {
  66. c[q][i] = (*this)[p][i];
  67. c[p][i] = (*this)[q][i];
  68. }
  69.  
  70. Value = c.Value;
  71. }
  72. private:
  73. std::vector<T> Value;
  74. int col;
  75. int row;
  76. };
  77.  
  78. int main(void)
  79. {
  80. MatrixData<double> a(M, N), b(M, N), c(M, N);
  81.  
  82. a[0][0] = 1.0;
  83. a[0][1] = 2.0;
  84. a[1][0] = 3.0;
  85. a[1][1] = 4.0;
  86. b[0][0] = 5.0;
  87. b[0][1] = 6.0;
  88. b[1][0] = 7.0;
  89. b[1][1] = 8.0;
  90.  
  91. std::cout << std::fixed;
  92.  
  93. c = a * b;
  94. c.ShowMatrix();
  95.  
  96. c.ChangeMatrix(0, 1);
  97. c.ShowMatrix();
  98. }
  99.  
Success #stdin #stdout 0.02s 2860KB
stdin
Standard input is empty
stdout
19.000000 22.000000 
43.000000 50.000000 
43.000000 50.000000 
19.000000 22.000000