Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Matrix {
- private:
- size_t w, h;
- double *data;
- public:
- constexpr Matrix() : data{ nullptr }, w{ 0 }, h{ 0 } {};
- Matrix(size_t width, size_t height) :w{width}, h{height}
- {
- data = new double[w * h];
- for (size_t i = 0; i < w * h; i++) {
- data[i] = 0;
- }
- }
- Matrix(const Matrix& other) : w{other.w}, h{other.w}
- {
- data = new double[w * h];
- for (size_t i = 0; i < w * h; i++) {
- data[i] = other.data[i];
- }
- }
- ~Matrix()
- {
- delete[] data;
- }
- size_t width() const { return w; }
- size_t height() const { return h; }
- double& operator()(size_t i, size_t j)
- {
- int idx = w*(j - 1) + (i - 1);
- if (idx < 0 || idx > w*h)
- throw std::out_of_range("");
- return data[idx];
- }
- const double& operator()(size_t i, size_t j) const
- {
- int idx = w*(j - 1) + (i - 1);
- if (idx < 0 || idx > w*h)
- throw std::out_of_range("");
- return data[idx];
- }
- };
- std::ostream& operator<<(std::ostream& os, const Matrix& matrix)
- {
- const size_t w = matrix.width();
- const size_t h = matrix.height();
- os << std::endl << '[';
- for (size_t i = 1; i <= w; i++) {
- if (i != 1)
- os << ' ';
- for (size_t j = 1; j <= h; j++) {
- os << matrix(i, j);
- if (j != h)
- os << "\t";
- }
- if (i == w)
- os << ']';
- os << std::endl;
- }
- return os;
- }
- int main()
- {
- auto m = Matrix(3, 3);
- std::cout << "m: " << m << std::endl;
- m(1, 1) = 1;
- m(3, 3) = 9;
- std::cout << "m: " << m << std::endl;
- auto m1 = Matrix(3, 3);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement