Skip to content

Instantly share code, notes, and snippets.

@leofun01
Last active October 28, 2019 08:17
Show Gist options
  • Select an option

  • Save leofun01/dfd440861045ad0583eecbb9f8b66dfe to your computer and use it in GitHub Desktop.

Select an option

Save leofun01/dfd440861045ad0583eecbb9f8b66dfe to your computer and use it in GitHub Desktop.
Matrix_for_topic_11158
// Main.cpp
#include <ctime>
#include <iostream>
#include "Matrix.h"
int main(int argc, char const *argv[]) {
Matrix<int> matrix(3, 5);
srand(time(nullptr));
matrix.init([]() -> int { return rand() % 10; });
/*//
matrix[0][0] = 2;
matrix[1][1] = 3;
matrix[2][2] = 4;
//*/
std::cout << "Matrix : " << matrix << "\r\n";
std::cout << "Trace : " << matrix.get_trace() << endl;
return 0;
}
// Matrix.h
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
using namespace std;
template<typename T>
class Matrix {
private:
size_t n, m, len;
T *a;
public:
Matrix(size_t n, size_t m) : n(n), m(m), len(n * m), a(new T[len]) {
for(size_t i(0); i < len; ++i)
a[i] = 0;
}
~Matrix() {
if(!a) return;
delete[] a;
a = nullptr;
}
T *operator [](size_t i) {
return (i >= 0 && i < n && a) ? i * m + a : nullptr;
}
T const *operator [](size_t i) const {
return (i >= 0 && i < n && a) ? i * m + a : nullptr;
}
T get_trace() const {
T trace(0);
if(!a) return trace;
size_t c = n < m ? n : m;
for(size_t i(0); i < c; ++i)
trace += (*this)[i][i];
return trace;
}
size_t get_n() const { return n; }
size_t get_m() const { return m; }
void init(T (*generator)()) {
for(size_t i(0); i < len; ++i)
a[i] = generator();
}
};
template<typename T>
ostream &operator <<(ostream &out, Matrix<T> const &matrix) {
size_t n(matrix.get_n()), m(matrix.get_m()), i(0), j(0);
T const *row(matrix[i]);
out << "[\r\n [ " << row[j];
for(++j; j < m; ++j)
out << ", " << row[j];
out << " ]";
for(++i; i < n; ++i) {
row = matrix[i];
out << ",\r\n [ " << row[j = 0];
for(++j; j < m; ++j)
out << ", " << row[j];
out << " ]";
}
out << "\r\n]";
return out;
}
#endif
@leofun01
Copy link
Author

Output :

Matrix : [
  [ 6, 0, 2, 1, 6 ],
  [ 6, 8, 3, 1, 8 ],
  [ 0, 4, 3, 4, 8 ]
]
Trace : 17

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment