matrix.cpp


1
#include <iostream>
2
#include <vector>
3
4
template <size_t rows, size_t cols, typename T>
5
class Matrix {
6
public:
7
    Matrix() {
8
        data.resize(rows, std::vector<T>(cols));
9
    }
10
11
    Matrix(const std::vector<std::vector<T>>& inputData) {
12
        if (inputData.size() != rows || inputData[0].size() != cols) {
13
            throw std::invalid_argument("Invalid matrix dimensions");
14
        }
15
16
        data = inputData;
17
    }
18
19
    Matrix<rows, cols, T> operator+(const Matrix<rows, cols, T>& other) const {
20
        Matrix<rows, cols, T> result;
21
22
        for (size_t i = 0; i < rows; i++) {
23
            for (size_t j = 0; j < cols; j++) {
24
                result[i][j] = data[i][j] + other[i][j];
25
            }
26
        }
27
28
        return result;
29
    }
30
31
    std::vector<T>& operator[](size_t rowIndex) {
32
        if (rowIndex >= rows) {
33
            throw std::out_of_range("Row index out of range");
34
        }
35
36
        return data[rowIndex];
37
    }
38
39
    const std::vector<T>& operator[](size_t rowIndex) const {
40
        if (rowIndex >= rows) {
41
            throw std::out_of_range("Row index out of range");
42
        }
43
44
        return data[rowIndex];
45
    }
46
47
    size_t numRows() const {
48
        return rows;
49
    }
50
51
    size_t numCols() const {
52
        return cols;
53
    }
54
55
private:
56
    std::vector<std::vector<T>> data;
57
};
58
59
template <size_t rows, size_t cols, typename T>
60
std::ostream& operator<<(std::ostream& os, const Matrix<rows, cols, T>& matrix) {
61
    for (size_t i = 0; i < rows; i++) {
62
        for (size_t j = 0; j < cols; j++) {
63
            os << matrix[i][j] << ' ';
64
        }
65
66
        os << '\n';
67
    }
68
69
    return os;
70
}
71
72
int main() {
73
    Matrix<3, 3, int> matrixA({ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} });
74
    Matrix<3, 3, int> matrixB({ {9, 8, 7}, {6, 5, 4}, {3, 2, 1} });
75
76
    Matrix<3, 3, int> matrixC = matrixA + matrixB;
77
78
    std::cout << "Matrix A:\n" << matrixA;
79
    std::cout << "Matrix B:\n" << matrixB;
80
    std::cout << "Matrix C (A + B):\n" << matrixC;
81
82
    return 0;
83
}