Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- template<typename T>
- class Matrix {
- private:
- std::vector<std::vector<T> >
- mat_;
- public:
- explicit Matrix(const std::vector<std::vector<T> > &mat) : mat_(mat) {}
- Matrix(size_t n, size_t m) {
- mat_.resize(n);
- mat_.resize(m);
- }
- const std::pair<size_t, size_t> size() const {
- if (mat_.empty())
- return {0, 0};
- return {mat_.size(), mat_[0].size()};
- }
- const std::vector<T> &operator[](size_t i) const {
- return mat_[i];
- }
- std::vector<T> &operator[](size_t i) {
- return mat_[i];
- }
- Matrix &operator+=(const Matrix &other) {
- auto[n, m] = this->size();
- for (size_t i = 0; i < n; ++i) {
- for (size_t j = 0; j < m; ++j)
- (*this)[i][j] += other[i][j];
- }
- return *this;
- }
- Matrix &operator*=(int alpha) {
- auto[n, m] = this->size();
- for (size_t i = 0; i < n; ++i) {
- for (size_t j = 0; j < m; ++j)
- (*this)[i][j] *= alpha;
- }
- return *this;
- }
- const Matrix& transposed() const {
- auto[n, m] = this->size();
- std::vector<std::vector<T> > result(m, std::vector<T>(n));
- for (size_t i = 0; i < n; ++i) {
- for (size_t j = 0; j < m; ++j) {
- result[j][i] = (*this)[i][j];
- }
- }
- Matrix rs(result);
- return rs;
- }
- void transpose() {
- *this = Matrix(transposed());
- }
- };
- template<typename T>
- Matrix<T> operator+(const Matrix<T> &one, const Matrix<T> &two) {
- Matrix tmp = one;
- return tmp += two;
- }
- template<typename T>
- Matrix<T> operator*(const Matrix<T> &one, int alpha) {
- Matrix tmp = one;
- return tmp *= alpha;
- }
- template<typename T>
- std::ostream &operator<<(std::ostream &out, const Matrix<T> &m) {
- auto[n, k] = m.size();
- for (size_t i = 0; i < n; ++i) {
- for (size_t j = 0; j < k; ++j) {
- out << m[i][j];
- if (j + 1 < k)
- out << '\t';
- }
- if (i + 1 < n)
- out << '\n';
- }
- return out;
- }
- int main() {
- std::vector<std::vector<int> > a(5), b(5);
- for (int i = 0; i < 5; ++i) {
- for (int j = 0; j < 5; ++j) {
- a[i].push_back(i + j + 2);
- b[i].push_back(4);
- }
- }
- Matrix m(a);
- Matrix t(b);
- auto dim = m.size();
- // std::cout << m << std::endl;
- // std::cout << dim.first << ' ' << dim.second << std::endl;
- Matrix rs = m.transposed();
- std::cout << rs << std::endl;
- //std::cout << t << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment