fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <memory>
  4.  
  5. template<typename T, size_t nDimensions>
  6. class MArray;
  7.  
  8. template<typename T, size_t nDimensions>
  9. class MArrayProxy : public MArrayProxy<T, nDimensions - 1>
  10. {
  11. public:
  12. MArrayProxy(MArray<T, nDimensions> &arr)
  13. : MArrayProxy<T, nDimensions - 1>(arr)
  14. {
  15. }
  16.  
  17. MArrayProxy<T, nDimensions - 1> &operator[](size_t idx)
  18. {
  19. this->position += idx * reinterpret_cast<MArray<T, nDimensions>&>(this->arr).elementSize;
  20. return *this;
  21. }
  22. };
  23.  
  24. template<typename T>
  25. class MArrayProxy<T, 1>
  26. {
  27. public:
  28. MArrayProxy(MArray<T, 1> &arr)
  29. : position(0), arr(arr)
  30. {
  31. }
  32.  
  33. T &operator[](size_t idx)
  34. {
  35. position += idx;
  36. return arr[position];
  37. }
  38.  
  39. protected:
  40. size_t position;
  41. MArray<T, 1> &arr;
  42. };
  43.  
  44.  
  45. template<typename T, size_t nDimensions>
  46. class MArray : public MArray<T, nDimensions - 1>
  47. {
  48. public:
  49. template<typename... SizeTypes>
  50. MArray(typename std::enable_if<sizeof...(SizeTypes) == nDimensions - 2, size_t>::type sz, size_t sz2, SizeTypes... sizes)
  51. : MArray<T, nDimensions - 1>(sz * sz2, sizes...)
  52. , elementSize(sz2 * MArray<T, nDimensions - 1>::elementSize)
  53. {
  54. }
  55.  
  56. MArrayProxy<T, nDimensions - 1> operator[](size_t idx)
  57. {
  58. return MArrayProxy<T, nDimensions>(*this)[idx];
  59. }
  60.  
  61. protected:
  62. friend class MArrayProxy<T, nDimensions>;
  63. size_t elementSize;
  64. };
  65.  
  66. template<typename T>
  67. class MArray<T, 1>
  68. {
  69. public:
  70. MArray(size_t sz)
  71. : data(new T[sz])
  72. {
  73. }
  74.  
  75. T &operator[](size_t idx)
  76. {
  77. return data[idx];
  78. }
  79.  
  80. protected:
  81. std::unique_ptr<T[]> data;
  82. const size_t elementSize = 1;
  83. };
  84.  
  85. int main()
  86. {
  87. int n, m;
  88. std::cin >> n >> m;
  89.  
  90. MArray<int, 2> matrix(n, m);
  91.  
  92. for (int i = 0; i < n; i++) {
  93. for (int j = 0; j < m; j++) {
  94. std::cin >> matrix[i][j];
  95. }
  96. }
  97.  
  98. for (int i = 0; i < n; i++) {
  99. for (int j = 0; j < m; j++) {
  100. std::cout << matrix[i][j] << " ";
  101. }
  102. std::cout << std::endl;
  103. }
  104. }
Success #stdin #stdout 0s 3472KB
stdin
2 3
1 2 3
4 5 6
stdout
1 2 3 
4 5 6