forked from natto1784/ooplab
96
lab2/4.cpp
Normal file
96
lab2/4.cpp
Normal file
@@ -0,0 +1,96 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
class Matrix {
|
||||
private:
|
||||
unsigned int r, c;
|
||||
vector<vector<int>> matrix;
|
||||
|
||||
public:
|
||||
Matrix() = default;
|
||||
Matrix(int, int);
|
||||
void init(vector<vector<int>>);
|
||||
unsigned int getRows();
|
||||
unsigned int getColumns();
|
||||
Matrix operator*(Matrix);
|
||||
void display();
|
||||
};
|
||||
|
||||
Matrix::Matrix(int r, int c) {
|
||||
this->r = r, this->c = c;
|
||||
this->matrix = vector<vector<int>>(r, vector<int>(c));
|
||||
}
|
||||
|
||||
void Matrix::init(vector<vector<int>> src) {
|
||||
unsigned int i, j;
|
||||
|
||||
if (this->r > src.size())
|
||||
exit(1);
|
||||
|
||||
for (i = 0; i < this->r; i++) {
|
||||
if (c > src[i].size())
|
||||
exit(1);
|
||||
|
||||
for (int j = 0; j < this->c; j++)
|
||||
this->matrix[i][j] = src[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
inline unsigned int Matrix::getRows() { return r; }
|
||||
|
||||
inline unsigned int Matrix::getColumns() { return c; }
|
||||
|
||||
Matrix Matrix::operator*(Matrix operand) {
|
||||
unsigned int i, j, k;
|
||||
unsigned int r, c;
|
||||
unsigned int common;
|
||||
Matrix m;
|
||||
|
||||
if (this->getColumns() != operand.getRows())
|
||||
exit(1);
|
||||
|
||||
r = this->getRows();
|
||||
c = operand.getColumns();
|
||||
|
||||
m = Matrix(r, c);
|
||||
|
||||
common = this->getColumns();
|
||||
|
||||
for (i = 0; i < r; i++) {
|
||||
for (j = 0; j < c; j++) {
|
||||
int s = 0;
|
||||
for (k = 0; k < common; k++)
|
||||
s += this->matrix[i][k] * operand.matrix[k][j];
|
||||
m.matrix[i][j] = s;
|
||||
}
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
void Matrix::display() {
|
||||
unsigned int i, j;
|
||||
|
||||
for (i = 0; i < this->r; i++) {
|
||||
for (j = 0; j < this->c; j++)
|
||||
cout << this->matrix[i][j] << ' ';
|
||||
cout << endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Matrix a(2, 3), b(3, 4);
|
||||
Matrix m;
|
||||
|
||||
a.init(vector<vector<int>>{{1, 2, -3}, {3, 2, 1}});
|
||||
|
||||
b.init(
|
||||
vector<vector<int>>{{1, -4, -4, 1}, {0, 4, 4, -34}, {3, 1231, 0, -9653}});
|
||||
|
||||
m = a * b;
|
||||
|
||||
m.display();
|
||||
|
||||
return 0;
|
||||
}
|
Reference in New Issue
Block a user