Matrix Class
Completed
Write a Matrix class (rows × cols of long long) with operator+, operator*, transpose() and operator<<. Read A and B (2×2) and print A+B, A×B and Aᵀ separated by --.
Input
Four lines: two rows of A, two rows of B.
Output
The three matrices separated by --.
Example
Input
1 2 3 4 5 6 7 8
Output
6 8 10 12 -- 19 22 43 50 -- 1 3 2 4
Editor
C++
Hints
Store the matrix in one flat vector and index it as i * cols + j.
Solution explanation
A flat vector is faster than a vector of vectors and keeps the class simple.
Show solution
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
public:
Matrix(size_t r, size_t c) : r_(r), c_(c), d_(r * c, 0) {}
long long &at(size_t i, size_t j) { return d_[i * c_ + j]; }
long long at(size_t i, size_t j) const { return d_[i * c_ + j]; }
Matrix operator+(const Matrix &o) const {
Matrix m(r_, c_);
for (size_t i = 0; i < d_.size(); i++) m.d_[i] = d_[i] + o.d_[i];
return m;
}
Matrix operator*(const Matrix &o) const {
Matrix m(r_, o.c_);
for (size_t i = 0; i < r_; i++)
for (size_t j = 0; j < o.c_; j++)
for (size_t k = 0; k < c_; k++) m.at(i, j) += at(i, k) * o.at(k, j);
return m;
}
Matrix transpose() const {
Matrix m(c_, r_);
for (size_t i = 0; i < r_; i++)
for (size_t j = 0; j < c_; j++) m.at(j, i) = at(i, j);
return m;
}
friend ostream &operator<<(ostream &out, const Matrix &m) {
for (size_t i = 0; i < m.r_; i++) {
for (size_t j = 0; j < m.c_; j++) out << m.at(i, j) << (j + 1 < m.c_ ? " " : "");
if (i + 1 < m.r_) out << "\n";
}
return out;
}
private:
size_t r_, c_;
vector<long long> d_;
};
Matrix read2x2() {
Matrix m(2, 2);
for (size_t i = 0; i < 2; i++)
for (size_t j = 0; j < 2; j++) cin >> m.at(i, j);
return m;
}
int main() {
Matrix a = read2x2(), b = read2x2();
cout << a + b << "\n--\n" << a * b << "\n--\n" << a.transpose() << "\n";
return 0;
}