matrix.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #pragma once
  2. #include <util/generic/noncopyable.h>
  3. #include <util/system/yassert.h>
  4. #include <util/system/defaults.h>
  5. #include <string.h>
  6. template <typename T>
  7. class TMatrix: TNonCopyable {
  8. // Constructor/Destructor
  9. public:
  10. TMatrix()
  11. : Buf(nullptr)
  12. , Arr(nullptr)
  13. , M(0)
  14. , N(0)
  15. , BufSize(0)
  16. {
  17. }
  18. TMatrix(size_t m, size_t n)
  19. : Buf(new T[m * n])
  20. , Arr(Buf)
  21. , M(m)
  22. , N(n)
  23. , BufSize(m * n)
  24. {
  25. }
  26. TMatrix(size_t m, size_t n, T* buf)
  27. : Buf(nullptr)
  28. , Arr(buf)
  29. , M(m)
  30. , N(n)
  31. , BufSize(m * n)
  32. {
  33. }
  34. ~TMatrix() {
  35. delete[] Buf;
  36. }
  37. // Properties/Methods
  38. public:
  39. void Clear() {
  40. M = N = 0;
  41. }
  42. void ReDim(size_t m, size_t n) {
  43. Y_ASSERT(m >= 1 && n >= 1);
  44. size_t newSize = m * n;
  45. if (newSize > BufSize) {
  46. T* newBuf = new T[newSize];
  47. delete[] Buf;
  48. Arr = Buf = newBuf;
  49. BufSize = newSize;
  50. }
  51. M = m;
  52. N = n;
  53. }
  54. size_t Width() const {
  55. return N;
  56. }
  57. size_t Height() const {
  58. return M;
  59. }
  60. // Access element matrix[i][j]
  61. T* operator[](size_t i) {
  62. Y_ASSERT(i >= 0 && i < M);
  63. return Arr + i * N;
  64. }
  65. // Access element matrix[i][j]
  66. const T* operator[](size_t i) const {
  67. Y_ASSERT(i >= 0 && i < M);
  68. return Arr + i * N;
  69. }
  70. // Access element matrix(i, j)
  71. T& operator()(size_t i, size_t j) {
  72. Y_ASSERT(i >= 0 && i < M && j >= 0 && j < N);
  73. return Arr[i * N + j];
  74. }
  75. // Access element matrix(i, j)
  76. const T& operator()(size_t i, size_t j) const {
  77. Y_ASSERT(i >= 0 && i < M && j >= 0 && j < N);
  78. return Arr[i * N + j];
  79. }
  80. void Zero() {
  81. memset((void*)Arr, 0, M * N * sizeof(T));
  82. }
  83. void Fill(T value) {
  84. for (T *p = Arr, *end = Arr + M * N; p < end; ++p)
  85. *p = value;
  86. }
  87. private:
  88. T* Buf;
  89. T* Arr;
  90. size_t M, N;
  91. size_t BufSize;
  92. };