Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- struct indices {
- int x, y;
- };
- class matrix {
- private:
- int Nx, Ny;
- double **A;
- public:
- matrix() : Nx(0), Ny(0), A(nullptr) {}
- matrix(int nx, int ny) : Nx(nx), Ny(ny) {
- A = new double*[Nx];
- for (int i = 0; i < Nx; ++i) {
- A[i] = new double[Ny];
- for (int j = 0; j < Ny; ++j) {
- A[i][j] = 0;
- }
- }
- }
- matrix(const matrix& other) : Nx(other.Nx), Ny(other.Ny) {
- A = new double*[Nx];
- for (int i = 0; i < Nx; ++i) {
- A[i] = new double[Ny];
- for (int j = 0; j < Ny; ++j) {
- A[i][j] = other.A[i][j];
- }
- }
- }
- ~matrix() {
- for (int i = 0; i < Nx; ++i) {
- delete[] A[i];
- }
- delete[] A;
- }
- matrix& operator=(const matrix& other) {
- matrix tmp(other);
- Nx = tmp.Nx;
- Ny = tmp.Ny;
- A = tmp.A;
- return *this;
- }
- double &operator[](const indices& idx) {
- return A[idx.x][idx.y];
- }
- friend std::ostream& operator<<(std::ostream& out, const matrix& mx) {
- for (int i = 0; i < mx.Nx; ++i) {
- for (int j = 0; j < mx.Ny; ++j) {
- out << mx.A[i][j] << " ";
- }
- out << "\n";
- }
- return out;
- }
- matrix operator*(const matrix& mx) {
- if (Ny != mx.Nx) {
- return matrix();
- }
- matrix tmp(Nx, mx.Ny);
- for (int i = 0; i < Nx; ++i) {
- for (int j = 0; j < mx.Ny; ++j) {
- for (int k = 0; k < Ny; ++k) {
- tmp.A[i][j] += A[i][k] * mx.A[k][j];
- }
- }
- }
- return tmp;
- }
- matrix operator+(const matrix& mx) {
- if (Nx != mx.Nx or Ny != mx.Ny) {
- return matrix();
- }
- matrix tmp(mx);
- for (int i = 0; i < Nx; ++i) {
- for (int j = 0; j < Ny; ++j) {
- tmp.A[i][j] += A[i][j];
- }
- }
- return tmp;
- }
- };
- int main() {
- matrix A(2, 2), B(2, 2);
- A[indices{.x = 0, .y = 0}] = 1;
- A[indices{.x = 0, .y = 1}] = 2;
- A[indices{.x = 1, .y = 0}] = 3;
- A[indices{.x = 1, .y = 1}] = 4;
- B[indices{.x = 0, .y = 0}] = 1;
- B[indices{.x = 0, .y = 1}] = 2;
- B[indices{.x = 1, .y = 0}] = 3;
- B[indices{.x = 1, .y = 1}] = 4;
- std::cout << A + B << '\n';
- std::cout << A * B << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement