Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. class Matrix {
  2. private:
  3.     size_t w, h;
  4.     double *data;
  5. public:
  6.     constexpr Matrix() : data{ nullptr }, w{ 0 }, h{ 0 } {};
  7.     Matrix(size_t width, size_t height) :w{width}, h{height}
  8.     {
  9.         data = new double[w * h];
  10.         for (size_t i = 0; i < w * h; i++) {
  11.             data[i] = 0;
  12.         }
  13.     }
  14.  
  15.     Matrix(const Matrix& other) : w{other.w}, h{other.w}
  16.     {
  17.         data = new double[w * h];
  18.         for (size_t i = 0; i < w * h; i++) {
  19.             data[i] = other.data[i];
  20.         }
  21.     }
  22.  
  23.     ~Matrix()
  24.     {
  25.         delete[] data;
  26.     }
  27.  
  28.     size_t width() const { return w; }
  29.     size_t height() const { return h; }
  30.    
  31.     double& operator()(size_t i, size_t j)
  32.     {
  33.         int idx = w*(j - 1) + (i - 1);
  34.         if (idx < 0 || idx > w*h)
  35.             throw std::out_of_range("");
  36.         return data[idx];
  37.     }
  38.    
  39.     const double& operator()(size_t i, size_t j) const
  40.     {
  41.         int idx = w*(j - 1) + (i - 1);
  42.         if (idx < 0 || idx > w*h)
  43.             throw std::out_of_range("");
  44.         return data[idx];
  45.     }
  46. };
  47.  
  48. std::ostream& operator<<(std::ostream& os, const Matrix& matrix)
  49. {
  50.     const size_t w = matrix.width();
  51.     const size_t h = matrix.height();
  52.  
  53.     os << std::endl << '[';
  54.     for (size_t i = 1; i <= w; i++) {
  55.         if (i != 1)
  56.             os << ' ';
  57.         for (size_t j = 1; j <= h; j++) {
  58.             os << matrix(i, j);
  59.             if (j != h)
  60.                 os << "\t";
  61.         }
  62.         if (i == w)
  63.             os << ']';
  64.         os << std::endl;
  65.     }
  66.  
  67.     return os;
  68. }
  69.  
  70. int main()
  71. {
  72.     auto m = Matrix(3, 3);
  73.     std::cout << "m: " << m << std::endl;
  74.     m(1, 1) = 1;
  75.     m(3, 3) = 9;
  76.     std::cout << "m: " << m << std::endl;
  77.  
  78.     auto m1 = Matrix(3, 3);
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement