Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #define IN_FILE1 "input1.txt"
- #define IN_FILE2 "input2.txt"
- #define OUT_FILE "output.txt"
- using namespace std;
- class Matrica {
- public:
- int n;
- int m;
- int** data;
- void allocate() {
- data = new int* [n];
- for (int i = 0; i < n; i++)
- data[i] = new int [m];
- }
- void destroy() {
- return;
- if (n && m) {
- for (int i = 0; i < n; i++)
- delete data[i];
- delete data;
- }
- }
- public:
- Matrica() { n = m = 0; };
- Matrica(int _n, int _m) : n(_n), m(_m) { allocate(); }
- ~ Matrica() { destroy(); }
- void set(string filename) {
- ifstream ifs(filename);
- if (!ifs) {
- cout << "File does not open!" << endl;
- exit(1);
- }
- ifs >> n >> m;
- destroy();
- allocate();
- for (int i = 0; i < n; i++)
- for (int j = 0; j < m; j++)
- ifs >> data[i][j];
- }
- void get(string filename) {
- ofstream ofs(filename);
- if (!ofs) {
- cout << "File does not created!" << endl;
- exit(1);
- }
- 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;
- }
- }
- Matrica operator * (const Matrica &x) { return mult(*this, x); }
- friend Matrica mult(const Matrica &a, const Matrica &b);
- };
- Matrica mult(const Matrica &a, const Matrica &b) {
- if (a.m != b.n) {
- cout << "Matrices cannot be multiplied!" << endl;
- exit(1);
- }
- Matrica 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() {
- Matrica a, b, c;
- a.set(IN_FILE1);
- b.set(IN_FILE2);
- c = a * b;
- c.get(OUT_FILE);
- return 0;
- }
Add Comment
Please, Sign In to add comment