Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <cassert>
- /*input file of first matrix*/
- #define IN_FA "inputA.txt"
- /*input file of second matrix*/
- #define IN_FB "inputB.txt"
- /*output file*/
- #define OUT_F "output.txt"
- using namespace std;
- /*class Matrix*/
- class Matrix {
- public:
- /*count of rows*/
- int n;
- /*count of columns*/
- int m;
- /*two-dimensional array*/
- int** data;
- /*function for allocating two-dimensional array*/
- void allocate() {
- data = new int* [n];
- for (int i = 0; i < n; i++)
- data[i] = new int [m];
- }
- /*function for destroying two-dimensional array*/
- void destroy() {
- return;
- if (n && m) {
- for (int i = 0; i < n; i++)
- delete data[i];
- delete data;
- }
- }
- public:
- /*constructor by default*/
- Matrix() { n = m = 0; };
- /*initializer list constructors*/
- Matrix(int _n, int _m) : n(_n), m(_m) { allocate(); }
- /*destructor*/
- ~ Matrix() { destroy(); }
- /*function set. Reading matrix from file*/
- void set(string filename) {
- ifstream ifs(filename);
- assert(ifs && "File does not open!");
- ifs >> n >> m;
- destroy();
- allocate();
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- ifs >> data[i][j];
- }
- /*function get. Writing matrix to file*/
- void get(string filename) {
- ofstream ofs(filename);
- assert(ofs && "File does not created!");
- ofs << "n = " << n << " m = " << m << endl;
- ofs << "Matrix:" << endl;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < m; j++)
- ofs << data[i][j] << " ";
- ofs << endl;
- }
- }
- /*assignation operator*/
- Matrix& operator = (const Matrix &x) {
- n = x.n; m = x.m;
- destroy();
- allocate();
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- data[i][j] = x.data[i][j];
- return *this;
- }
- /*multiplication operator*/
- Matrix operator * (const Matrix &x) { return mult(*this, x); }
- /*friend function for multiplication*/
- friend Matrix mult(const Matrix &a, const Matrix &b);
- };
- /*multiplication function*/
- Matrix mult(const Matrix &a, const Matrix &b) {
- assert(a.m == b.n && "Matrices cannot be multiplied!");
- Matrix c(a.n, b.m);
- for (int i = 0; i < c.n; i++)
- for (int j = 0; j < c.m; j++) {
- c.data[i][j] = 0;
- for (int k = 0; k < a.m; k++)
- c.data[i][j] += a.data[i][k] * b.data[k][j];
- }
- return c;
- }
- int main() {
- Matrix a, b, c;
- /*reading from file*/
- a.set(IN_FA);
- b.set(IN_FB);
- /*calculating*/
- c = a * b;
- /*writing to file*/
- c.get(OUT_F);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement