fork download
  1. #include <iostream>
  2. #include <iomanip>
  3.  
  4. using namespace std;
  5.  
  6. class Matrix
  7. {
  8. size_t rows, cols;
  9. int **data;
  10. void swap(Matrix&M)
  11. {
  12. std::swap(data,M.data);
  13. std::swap(rows,M.rows);
  14. std::swap(cols,M.cols);
  15. }
  16. public:
  17. Matrix(size_t rows, size_t cols):rows(rows),cols(cols)
  18. {
  19. data = new int *[rows];
  20. for(size_t i = 0; i < rows; i++)
  21. data[i] = new int[cols];
  22. }
  23. ~Matrix()
  24. {
  25. for (size_t i = 0; i < rows; i++)
  26. delete[] data[i];
  27. delete[] data;
  28. }
  29.  
  30. Matrix(const Matrix&M):Matrix(M.rows,M.cols)
  31. {
  32. for(size_t i = 0; i < rows; i++)
  33. for(size_t j = 0; j < cols; j++)
  34. data[i][j] = M.data[i][j];
  35. }
  36.  
  37. Matrix& operator = (const Matrix& M)
  38. {
  39. Matrix tmp(M);
  40. swap(tmp);
  41. return *this;
  42. }
  43.  
  44. friend ostream& operator<<(ostream&os, const Matrix& M);
  45. friend istream& operator>>(istream&is, Matrix& M);
  46.  
  47. Matrix transpose()
  48. {
  49. Matrix temp(cols,rows);
  50. for(size_t i = 0; i < rows; i++)
  51. for(size_t j = 0; j < cols; j++)
  52. temp.data[j][i] = data[i][j];
  53. return temp;
  54. }
  55.  
  56. };
  57.  
  58.  
  59. ostream& operator<<(ostream&os, const Matrix& M)
  60. {
  61. for(size_t i = 0; i < M.rows; i++)
  62. {
  63. for(size_t j = 0; j < M.cols; j++)
  64. {
  65. os << M.data[i][j]<< " ";
  66. }
  67. os << "\n";
  68. }
  69. return os;
  70. }
  71.  
  72. istream& operator>>(istream&is, Matrix& M)
  73. {
  74. for(size_t i = 0; i < M.rows; i++)
  75. {
  76. for(size_t j = 0; j < M.cols; j++)
  77. {
  78. cout << "Matrix[" << i << "][" << j << "] = ";
  79. is >> M.data[i][j];
  80. }
  81. }
  82. return is;
  83. }
  84.  
  85. int main()
  86. {
  87. int num_of_cols, num_of_rows;
  88. cout <<"input the num of cols and rows"<<endl;
  89. cin >> num_of_rows >> num_of_cols;
  90.  
  91. Matrix ob1(num_of_rows, num_of_cols);
  92. cin >> ob1;
  93. cout << "\n\n" << ob1 << "\n\n";
  94.  
  95. Matrix ob2 = ob1.transpose();
  96.  
  97. cout << ob2 << "\n\n";
  98. }
  99.  
  100.  
Success #stdin #stdout 0.01s 5316KB
stdin
2 5
0 1 2 3 4 5 6 7 8 9
stdout
input the num of cols and rows
Matrix[0][0] = Matrix[0][1] = Matrix[0][2] = Matrix[0][3] = Matrix[0][4] = Matrix[1][0] = Matrix[1][1] = Matrix[1][2] = Matrix[1][3] = Matrix[1][4] = 

0 1 2 3 4 
5 6 7 8 9 


0 5 
1 6 
2 7 
3 8 
4 9