Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- template <class T>
- class Matrix {
- private:
- vector<vector<T>> m;
- public:
- Matrix(const vector<vector<T>>& mat) : m(mat) {}
- friend ostream& operator<<(ostream& out, const Matrix<T>& mat) {
- string line_sep;
- for (auto& line : mat.m) {
- out << line_sep;
- string col_sep;
- for (const auto& elem : line) {
- out << col_sep << elem;
- col_sep = "\t";
- }
- line_sep = "\n";
- }
- return out;
- }
- pair<size_t, size_t> size() const {
- if (m.empty()) {
- return{ 0, 0 };
- } else {
- return{ m.size(), m[0].size() };
- }
- }
- Matrix& operator +=(Matrix& other) {
- for (int i = 0; i < m.size(); ++i) {
- for (int j = 0; j < m[0].size(); ++j) {
- m[i][j] += other.m[i][j];
- }
- }
- return *this;
- }
- template <class D>
- Matrix& operator *=(D lambda) {
- for (unsigned int i = 0; i < m.size(); ++i) {
- for (unsigned int j = 0; j < m[0].size(); ++j) {
- m[i][j] *= lambda;
- }
- }
- return *this;
- }
- Matrix& transpose() {
- int col = m[0].size();
- int row = m.size();
- vector<vector<T>> transp(col, vector<T>(row));
- for (int i = 0; i < row; ++i) {
- for (int j = 0; j < col; ++j) {
- transp[j][i] = m[i][j];
- }
- }
- m = transp;
- return *this;
- }
- Matrix transposed() const {
- Matrix transp = m;
- return transp.transpose();
- }
- Matrix& operator *=(const Matrix& other) {
- int row1 = m.size();
- int col2 = other.m[0].size();
- int col1 = m[0].size();
- vector<vector<T>> multip(row1, vector<T>(col2));
- for (int i = 0; i < row1; ++i) {
- for (int j = 0; j < col2; ++j) {
- for (int k = 0; k < col1; ++k) {
- multip[i][j] += m[i][k] * other.m[k][j];
- }
- }
- }
- m = multip;
- return *this;
- }
- };
- template <class T>
- Matrix<T> operator + (Matrix<T> m1, const Matrix<T>& m2) {
- return m1 += m2;
- }
- template <class T, class D>
- Matrix<T> operator * (Matrix<T> m1, const D& lambda) {
- return m1 *= lambda;
- }
- template <class T>
- Matrix<T> operator * (Matrix<T> m1, const Matrix<T>& m2) {
- return m1 *= m2;
- }
Advertisement
Add Comment
Please, Sign In to add comment