fork download
  1. #include <vector>
  2. #include <cstdlib>
  3. #include <iostream>
  4.  
  5. template <typename T>
  6. class Matrix_Proxy
  7. {
  8. public:
  9. Matrix_Proxy(std::vector<T>& _ref, size_t _size) : ref(_ref), size(_size)
  10. {}
  11. T& operator[](int i)
  12. {
  13. return ref[i];
  14. }
  15.  
  16. const T& operator[](int i) const
  17. {
  18. return ref[i];
  19. }
  20.  
  21. private:
  22. std::vector<T>& ref;
  23. size_t size;
  24.  
  25. };
  26.  
  27. template <typename T>
  28. class Matrix_Proxy_Const
  29. {
  30. public:
  31. Matrix_Proxy_Const(const std::vector<T>& _ref, size_t _size) : ref(_ref), size(_size)
  32. {}
  33.  
  34. const T& operator[](int i) const
  35. {
  36. return ref[i];
  37. }
  38.  
  39. private:
  40. const std::vector<T>& ref;
  41. size_t size;
  42.  
  43. };
  44.  
  45.  
  46. template <typename T>
  47. class Matrix
  48. {
  49. public:
  50. Matrix(size_t x) : values(x), size(x)
  51. {
  52. for(auto&& y : values)
  53. {
  54. y.resize(x);
  55. for(auto&& x : y)
  56. x = 0;
  57. }
  58. }
  59.  
  60. Matrix_Proxy<T> operator [] (int i)
  61. {
  62. return Matrix_Proxy<T>(values[i],size);
  63. }
  64.  
  65. const Matrix_Proxy_Const<T> operator [] (int i) const
  66. {
  67. return Matrix_Proxy_Const<T>(values[i],size);
  68. }
  69.  
  70. private:
  71. std::vector<std::vector<T>> values;
  72. size_t size;
  73. };
  74.  
  75. int main()
  76. {
  77. Matrix<int> intMat(5); //FINE
  78. std::cout << intMat[2][2] << std::endl; //FINE
  79.  
  80. const Matrix<int> cintMat(5); //FINE
  81. std::cout << cintMat[2][2] << std::endl; //FINE
  82.  
  83. }
  84.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
0
0