fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <utility>
  5.  
  6. class Matrix {
  7. std::string **m;
  8. int m_x, m_y;
  9. public:
  10. Matrix(int x = 0, int y = 0) : m_x(x), m_y(y) {
  11. m = new std::string*[x];
  12. for (int i = 0; i < x; ++i)
  13. m[i] = new std::string[y];
  14. }
  15.  
  16. Matrix(const Matrix &src) : m_x(src.m_x), m_y(src.m_y) {
  17. m = new std::string*[m_x];
  18. for (int i = 0; i < m_x; ++i) {
  19. m[i] = new std::string[m_y];
  20. for (int j = 0; j < m_y; ++j) {
  21. m[i][j] = src.m[i][j];
  22. }
  23. }
  24. }
  25.  
  26. ~Matrix() {
  27. for (int i = 0; i < m_x; ++i)
  28. delete[] m[i];
  29. delete[] m;
  30. }
  31.  
  32. Matrix& operator=(const Matrix &rhs) {
  33. if (&rhs != this) {
  34. Matrix temp(rhs);
  35. std::swap(m, temp.m);
  36. std::swap(m_x, temp.m_x);
  37. std::swap(m_y, temp.m_y);
  38. }
  39. return *this;
  40. }
  41.  
  42. void print() const {
  43. for(int i = 0; i < m_x; ++i) {
  44. for (int j = 0; j < m_y; ++j) {
  45. std::cout << '[' << m[i][j] << ']';
  46. }
  47. std::cout << std::endl;
  48. }
  49. }
  50.  
  51. class Proxy {
  52. std::string *mm;
  53. public:
  54. Proxy(std::string *s) : mm(s) {}
  55.  
  56. std::string& operator[](int index) {
  57. return mm[index];
  58. }
  59. };
  60.  
  61. Proxy operator[](int index) {
  62. return Proxy(m[index]);
  63. }
  64. };
  65.  
  66. int main()
  67. {
  68. Matrix m(5, 5);
  69. m.print();
  70. std::cout << std::endl;
  71.  
  72. m[2][2] = "It Works";
  73. std::cout << m[2][2] << std::endl;
  74. m.print();
  75. std::cout << std::endl;
  76.  
  77. Matrix m2(m);
  78. std::cout << m2[2][2] << std::endl;
  79. m2.print();
  80. std::cout << std::endl;
  81.  
  82. Matrix m3;
  83. m3 = m2;
  84. std::cout << m3[2][2] << std::endl;
  85. m3.print();
  86.  
  87. return 0;
  88. }
Success #stdin #stdout 0s 5596KB
stdin
Standard input is empty
stdout
[][][][][]
[][][][][]
[][][][][]
[][][][][]
[][][][][]

It Works
[][][][][]
[][][][][]
[][][It Works][][]
[][][][][]
[][][][][]

It Works
[][][][][]
[][][][][]
[][][It Works][][]
[][][][][]
[][][][][]

It Works
[][][][][]
[][][][][]
[][][It Works][][]
[][][][][]
[][][][][]