Matrix class content using shared_ptr? - c++

class Matrix
{
private:
int rows;
int cols;
int** Mat;
public:
Matrix(){}
Matrix(const int& rows, const int& cols):rows(rows),cols(cols)
{
Mat = new int* [cols];
for (int i = 0; i < rows; i++)
{
Mat[i] = new int[cols]();
}
}
Matrix operator +(const Matrix& other)const
{
Matrix temp(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp.Mat[i][j] += other.Mat[i][j] + Mat[i][j];
return temp;
}
My question is regarding how I'd use shared_ptr and make_shared to replace int** Mat? and, after that, how do I use it in the constructor and operator+? It's a custom matrix class that should add matrices

#include <iostream>
#include <memory>
#include <cassert>
class Matrix {
private:
int rows;
int cols;
std::shared_ptr<std::shared_ptr<int>> Mat;
public:
Matrix() = default;
Matrix(const int& rows, const int& cols) : rows(rows), cols(cols)
{
Mat.reset(new std::shared_ptr<int>[rows], [](std::shared_ptr<int>* p) { delete[] p; });
for (int i = 0; i < rows; ++i)
{
Mat.get()[i].reset(new int[cols], [](int* p) { delete[] p; });
}
for (int i = 0; i < (*this).rows; ++i)
for (int j = 0; j < (*this).cols; ++j)
(*this)[i][j] = 0;
}
int* operator[](const int& index) const
{
return Mat.get()[index].get();
}
Matrix(const Matrix& other) : cols(other.cols), rows(other.rows)
{
Mat.reset(new std::shared_ptr<int>[rows], [](std::shared_ptr<int>* p) { delete[] p; });
for (int i = 0; i < rows; ++i)
{
Mat.get()[i].reset(new int[other.cols], [](int* p) { delete[] p; });
}
for (int i = 0; i < other.rows; i++)
for (int j = 0; j < other.cols; j++)
(*this)[i][j] = other[i][j];
}
Matrix& operator=(const Matrix& other)
{
if (Mat != other.Mat && cols == other.cols && rows == other.rows)
{
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
(*this)[i][j] = other[i][j];
return *this;
}
else
return *this;
}
Matrix operator+(const Matrix& other) const
{
Matrix temp(rows, cols);
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp[i][j] += other[i][j] + (*this)[i][j];
return temp;
}
friend std::ostream& operator<<(std::ostream& os, Matrix& m)
{
for (int i = 0; i < m.rows; ++i)
{
for (int j = 0; j < m.cols; ++j)
{
os << m[i][j] << " ";
}
os << std::endl;
}
return os;
}
};
int main()
{
Matrix a(2, 2);
a[0][0] = 1;
a[0][1] = 1;
std::cout << a << std::endl;
Matrix b(2, 2);
b[1][1] = 1;
b[1][0] = 1;
std::cout << b << std::endl;
b[1][0] = 9;
Matrix c(a);
c[0][0] = 6;
std::cout << c << std::endl;
Matrix d = b;
std::cout << d << std::endl;
Matrix e = a + b;
std::cout << e << std::endl;
}
I have solved it myself in the end :D

Related

Matrix C++ problem with overloading operators

I'm making simple matrix calculator for school project. I tried to use overloading operators but I have problem with operator "=". I checked it in debugger in Visual Studio and after assigning data from matrix A to matrix X all of data disappears. How should I repair this? Thank you in advance for your help and advice.
#include <iostream>
#include <vector>
#include <conio.h>
#include <stdlib.h>
using std::vector;
class Matrix {
private:
int rows, cols;
vector<vector<double>> matrix;
public:
Matrix(int r = 0, int c = 0) : rows(r), cols(c) {
std::vector<std::vector<double>> M(rows, std::vector<double>(cols));
matrix = M;
}
~Matrix() {}
// void operator+(const Matrix &rhs);
double get_rows() { return rows; }
double get_cols() { return cols; }
void set_matrix_value() {
std::cout << "Put values in your matrix\n";
for(int i = 0; i < matrix.size(); i++) {
for(int j = 0; j < matrix[i].size(); j++) {
// this->matrix[i][j] = int(_getch() - '0');
std::cin >> matrix[i][j];
}
}
}
void display_matrix() {
for(int i = 0; i < matrix.size(); i++) {
std::cout << "|";
for(int j = 0; j < matrix[i].size(); j++) {
std::cout << matrix[i][j];
if(j != matrix[i].size() - 1) {
std::cout << " ";
}
}
std::cout << "|\n";
}
}
Matrix operator=(const Matrix& M) {
rows = M.rows;
cols = M.cols;
Matrix new_matrix(rows, cols);
std::vector<std::vector<double>> m(rows, std::vector<double>(cols));
new_matrix.matrix = m;
for(int i = 0; i < m.size(); i++) {
for(int j = 0; j < m[i].size(); j++) {
new_matrix.matrix[i][j] = M.matrix[i][j];
}
}
return new_matrix;
}
Matrix operator+(const Matrix& m) {
if(rows != m.rows && cols != m.cols) {
std::cout << "Matrix sizes do not match. Write martix again.";
return (*this);
}
Matrix new_matrix(rows, cols);
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
new_matrix.matrix[i][j] = matrix[i][j] + m.matrix[i][j];
}
}
return new_matrix;
}
};
int main() {
// int k;
// int rows, cols;
Matrix X;
// std::cout << "Welcome in Matrix Mode!\n";
X.display_matrix();
Matrix A(3, 3);
A.set_matrix_value();
A.display_matrix();
X = A;
std::cout << X.get_rows() << " " << X.get_cols();
X.display_matrix();
}

overloading the addition and multiplication operators for the matrix class

I implement the overloading of the addition and multiplication operators for the matrix class. I can't understand where the error is, or rather, I guess that there is an error in the declaration of operators, but I have no idea how to fix it specifically.
Can someone suggest a good book on object oriented programming. I feel that I am clearly lacking information
#include <iostream>
using namespace std;
template <typename T>
class MATRIX
{
private:
T** M;
int m;
int n;
public:
MATRIX()
{
n = m = 0;
M = nullptr;
}
MATRIX(int _m, int _n)
{
m = _m;
n = _n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*)new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = 0;
}
MATRIX(const MATRIX& _M)
{
m = _M.m;
n = _M.n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*) new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = _M.M[i][j];
}
T GetMij(int i, int j)
{
if ((m > 0) && (n > 0))
return M[i][j];
else
return 0;
}
void SetMij(int i, int j, T value)
{
if ((i < 0) || (i >= m))
return;
if ((j < 0) || (j >= n))
return;
M[i][j] = value;
}
void Print(const char* ObjName)
{
cout << "Object: " << ObjName << endl;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
cout << M[i][j] << "\t";
cout << endl;
}
cout << "---------------------" << endl << endl;
}
MATRIX operator=(const MATRIX& _M)
{
if (n > 0)
{
for (int i = 0; i < m; i++)
delete[] M[i];
}
if (m > 0)
{
delete[] M;
}
m = _M.m;
n = _M.n;
M = (T**) new T * [m];
for (int i = 0; i < m; i++)
M[i] = (T*) new T[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
M[i][j] = _M.M[i][j];
return *this;
}
MATRIX operator+(const MATRIX& _M) {
MATRIX M6(_M.n, _M.m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
M6.M[i][j] = _M.M[i][j]+this-> M[i][j];
}
return M6;
}
MATRIX operator*(const MATRIX& _M) {
MATRIX M5(_M.n, _M.m);
for (int i = 0; i < _M.n; i++)
{
for (int j = 0; j < _M.m; j++)
{
for (int k = 0; k < m; k++)
{
M5.M[i][j] += M[i][k]*_M.M[k][j];
}
}
}
return M5;
}
bool operator ==(const MATRIX& _M) {
return this->n == _M.n && this->m == _M.m;
}
bool operator !=(const MATRIX& _M) {
return !(this->n == _M.n && this->m == _M.m);
}
~MATRIX()
{
if (n > 0)
{
for (int i = 0; i < m; i++)
delete[] M[i];
}
if (m > 0)
delete[] M;
}
};
void main()
{
MATRIX<int> M(2, 3);
M.Print("M");
int i, j;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
M.SetMij(i, j, i + j);
M.Print("M");
MATRIX<int> M2 = M;
M2.Print("M2");
MATRIX<int> M3;
M3 = M;
M3.Print("M3");
MATRIX<int> M4;
M4 = M3 = M2 = M;
M4.Print("M4");
////////////////////////
bool result = M == M3;// ==
if (result == 1) {
cout << "true";
}
else if (result == 0) {
cout << "false";
}
cout << endl << "---------------------" << endl << endl;
//////////////////////////
bool result1 = M != M3;// !=
if (result1 == 1) {
cout << "true";
}
else if (result1 == 0) {
cout << "false";
}
cout << endl << "---------------------" << endl << endl;
MATRIX<int> M1;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++)
M1.SetMij(i, j, i + j);
M1.Print("M1");
M.Print("M");
MATRIX<int> M6 = M + M1;
M6.Print("M");
MATRIX<int> M5 = M * M1;
M5.Print("M");
}```
thanks in advance
[enter image description here][1]
[1]: https://i.stack.imgur.com/TjEOp.png
I belive that std::vector is better
MATRIX() {}
MATRIX(int r, int c) : M(r * c, T()) , rows(r), cols(c) { }
// Does not need copy constructor
// Does not need operator =
// Does not need destructor
also you can proxy row and cols to overload []
MATRIX<int> x(3,3);
x[2][2] = 10;
also a generating function is welcome
template<typename GenT> void generate( GenT gen ) {...}
https://godbolt.org/z/dK6Tqc

How to write a friend (operator) method in a template?

So I'm trying to overload the operator + in a template class.
the code compiles and runs but crashes at the use of the operator +.
tried so many things, I think it's a syntax problem? any advice would be appreciated!
The operator = is overloaded and works.
Matrix.h
template <int row, int col, class T = int>
class Matrix
{
int rows;
int cols;
T** mat;
public:
Matrix(int defVal = 0) {
rows = row;
cols = col;
memory();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = defVal;
}
~Matrix() {
del();
}
Matrix(const Matrix& other) {
*this = other;
}
const Matrix& operator=(const Matrix& other) {
if (&other != this)
{
rows = other.rows;
cols = other.cols;
del();
memory();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = other.mat[i][j];
}
return *this;
}
friend ostream& operator<<(ostream& os, const Matrix& m) {
for (int i = 0; i < m.cols; i++)
{
for (int j = 0; j < m.rows; j++)
os << m.mat[i][j] << " ";
os << endl;
}
return os;
}
friend Matrix operator+(const Matrix& other, T num) {
Matrix temp = other;
for (int i = 0; i < temp.rows; i++)
for (int j = 0; j < temp.cols; j++)
temp.mat[i][j] += num;
return temp;
}
void memory(){
mat = new T * [rows];
for (int i = 0; i < rows; i++)
mat[i] = new T[cols];
}
void del(){
for (int i = 0; i < rows; i++)
delete[] mat[i];
delete[] mat;
}
};
main.cpp
int main() {
Matrix<4, 4> mat;
std::cout << mat << std::endl;
Matrix<4, 4> identity(1);
std::cout << identity + 3 << std::endl; //crashes here
return 0;
}
if you need other parts of the code let me know! Thanks in advance!
Your copy constructor and assignment looks suspicious, you del after changing rows and cols, without initialising anything.
I expect it should be
Matrix(const Matrix& other) : rows(0), cols(0), mat(nullptr) {
*this = other;
}
const Matrix& operator=(const Matrix& other) {
if (&other != this)
{
del(); // clean up first
rows = other.rows;
cols = other.cols;
memory();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = other.mat[i][j];
}
return *this;
}
As an aside, I wouldn't use dynamic allocation here at all, and instead
template <typename T, size_t rows, size_t cols>
class Matrix
{
std::array<std::array<T, cols>, rows> mat;
public:
Matrix(T defVal = {}) {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = defVal;
}
friend std::ostream& operator<<(std::ostream& os, const Matrix& m) {
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
os << m.mat[i][j] << " ";
os << std::endl;
}
return os;
}
friend Matrix operator+(Matrix other, T num) {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
other.mat[i][j] += num;
return other;
}
// No need for any special members
};

Access violation reading location - creating matrix class

This is supposed to be my HW in OOP course. SO i asked to create matrix class. Code works fine - all methods and new operands works fine BUT when my D`tor is empty and when i write there code to free memory i get this error. Thanks for help
int main()
{
MyMatrix m1(3, 3);
MyMatrix m2(3, 3);
MyMatrix res(3, 3);
m1.Set();
m2.Set();
cout << m1;
cout << m2;
res = m1 + m2;
cout << res;
}
CPP
MyMatrix::MyMatrix(int row, int col) // C`tor with specific data
{
n = row;
m = col;
matrix = new int* [n]; // Memory allocation for rows
for (int i = 0; i < n; i++)
{
matrix[i] = new int[m]; // Memory Allocation for columns
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = 0;
}
}
}
MyMatrix::~MyMatrix() // Default d`tor
{
for (int i = 0; i < n; i++)
{
delete[] matrix[i];
}
delete[] matrix;
}
void MyMatrix::Set()
{
cout << "Enter new row" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> matrix[i][j];
}
if (i != (n - 1))
{
cout << "Enter new row" << endl;
}
}
}
ostream& operator<<(ostream& out, const MyMatrix& matrix)
{
for (int i = 0; i < matrix.n; i++)
{
//run in loop on every column.
for (int j = 0; j < matrix.m; j++)
//print value with a space.
out << matrix.matrix[i][j] << "t";
//at the end of every row jump line.
out << endl;
}
out << endl;
return out;
}
MyMatrix& MyMatrix::operator= (const MyMatrix& mat1)
{
n = mat1.n;
m = mat1.m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
matrix[i][j] = mat1.matrix[i][j];
}
}
return *this;
}
const MyMatrix MyMatrix::operator+(const MyMatrix& mat1) const
{
MyMatrix temp(n, m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
temp.matrix[i][j] = matrix[i][j] + mat1.matrix[i][j];
}
}
return temp;
}
H file
class MyMatrix
{
private:
int **matrix;
int n, m;
public:
MyMatrix(int a, int b);
~MyMatrix();
void Set();
const MyMatrix operator+ (const MyMatrix& mat1) const;
MyMatrix& operator= (const MyMatrix& mat1);
friend ostream& operator<<(ostream& out, const MyMatrix& matrix);
};

C++ OOP - Arrays (matrices) multiplication, deleting object [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 7 years ago.
I am writing simple C++ application to multiply two matrices. Yes, I am aware this version doesn't check e.g. whether number of rows is greater than zero.
I can create two objects using a default constructor and I can create third object (a result of multiplication of two previous objects of the same class). I can't however correctly delete this third object. When I try, an "Access violation reading location" exception is throw. Can you tell me what am I missing? Is there something I forget to initialize? This exception is only thrown when using myThirdFunction.
Any other advice on making this code better is welcome :)
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
class MyArray
{
int Variable1 = 0;
int Variable2 = 0;
float ** myArray;
public:
MyArray() : Variable1(0), Variable2(0){ myFunction(); }
MyArray (int variable1, int variable2) : Variable1(variable1):
Variable2(variable2){ myFunction(); }
MyArray(const MyArray &myArrayA, const MyArray &myArrayB) :
Variable1(myArrayA.Variable1), Variable2(myArrayB.Variable2)
{ myThirdFunction(myArrayA, myArrayB); }
MyArray(const MyArray &myArray)
{ Variable1=myArray.Variable1; Variable2 = myArray.Variable2;
this->myArray =myArray.myArray; }
void myFunction() {
cin >> Variable1;
cin >> Variable2;
myArray = new float*[Variable1];
myOtherFunction();
}
void myOtherFunction() {
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = rand() % (10 - 0) + 0;
}
}
void myThirdFunction(MyArray myArrayA, MyArray myArrayB)
{
Variable1 = myArrayA.Variable1;
Variable2 = myArrayB.Variable2;
myArray = new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
{
float tempVariable = 0;
for (int q = 0; q < myArrayA.Variable2; ++q)
{
tempVariable += myArrayA.myArray[i][q] * myArrayB.myArray[q][j];
}
myArray[i][j] = tempVariable;
}
}
}
void displayMyArray() {
for (int i = 0; i < Variable1; ++i)
{
for (int j = 0; j < Variable2; ++j)
cout << myArray[i][j] << '\t';
cout << endl;
}
}
~MyArray() {
for (int i = 0; i < Variable1; ++i)
{
delete[] myArray[i];
}
delete[]myArray;
}
};
int main(){
srand(time(0));
MyArray myArrayA;
myArrayA.displayMyArray();
cout << endl;
MyArray myArrayB;
myArrayB.displayMyArray();
cout << endl;
MyArray myArrayC(myArrayA, myArrayB);
myArrayC.displayMyArray();
getchar();
getchar();
return 0;
}
Thanks :)
The member myArray is a pointer, and in your copy constructor you just copy the pointer without creating a new array. Because myThirdFunction takes both arguments by value, it creates two copies of the original objects. And because the copy constructor doesn't create a new value, when those two copies go out of scope at the end of the function, the original pointers now point to deallocated memory. Whenever the original two objects are destroyed, the destructor tries to delete memory that was already deleted.
From the beginning, you have this constructor:
MyArray(const MyArray &myArrayA, const MyArray &myArrayB)
{
myThirdFunction(myArrayA, myArrayB); //This call creates two new objects
}
The signature of myThirdFunction being void myThirdFunction(MyArray myArrayA, MyArray myArrayB), you pass by value and create two new copies. That calls the copy constructors for the two parameters:
MyArray(const MyArray &myArray)
{
this->myArray =myArray.myArray; //shallow copy, very bad
}
The new objects now point to the same memory as the originals. So, when they are destroyed at the end of myThirdFunction, the original pointers become garbage. In a broad view, this happens. float* p = new float; delete p; delete p; The solution is to make the copy constructor actually copy the elements, not the pointers:
MyArray(const MyArray &p_copy) //The name confused me so I changed it
{
Variable1 = p_copy.Variable1;
Variable2 = p_copy.Variable2;
myArray new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = p_copy.myArray[i][j];
}
}
In addition, you probably want to pass to myThirdFunction by constant reference.
void myThirdFunction(const MyArray& myArrayA, const MyArray& myArrayB)
I don't see a need to create two temporary objects here.
At the first time this code will works.
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
class MyArray
{
int Variable1;
int Variable2;
float ** myArray;
public:
MyArray() : myArray(NULL), Variable1(0), Variable2(0) // initialize pointers with NULL is important
{
myFunction();
}
MyArray (int variable1, int variable2) : myArray(NULL), Variable1(variable1),
Variable2(variable2)
{
myFunction();
}
MyArray(const MyArray &myArrayA, const MyArray &myArrayB) : myArray(NULL),
Variable1(myArrayA.Variable1), Variable2(myArrayB.Variable2)
{
myThirdFunction(myArrayA, myArrayB);
}
MyArray(const MyArray &myArray)
{
Variable1=myArray.Variable1; Variable2 = myArray.Variable2;
this->myArray =myArray.myArray;
}
void myFunction()
{
cin >> Variable1;
cin >> Variable2;
myArray = new float*[Variable1];
myOtherFunction();
}
void myOtherFunction()
{
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
myArray[i][j] = rand() % (10 - 0) + 0;
}
}
void myThirdFunction(MyArray myArrayA, MyArray myArrayB)
{
// cols of first must be same as rows of second
if (myArrayA.Variable2 != myArrayB.Variable1)
return;
// memory must be cleaned before new array creation
clearArray();
Variable1 = myArrayA.Variable1;
Variable2 = myArrayB.Variable2;
myArray = new float*[Variable1];
for (int i = 0; i < Variable1; ++i)
{
myArray[i] = new float[Variable2];
for (int j = 0; j < Variable2; ++j)
{
float tempVariable = 0;
for (int q = 0; q < myArrayA.Variable2; ++q)
{
tempVariable += myArrayA.myArray[i][q] * myArrayB.myArray[q][j];
}
myArray[i][j] = tempVariable;
}
}
}
void displayMyArray()
{
for (int i = 0; i < Variable1; ++i)
{
for (int j = 0; j < Variable2; ++j)
cout << myArray[i][j] << '\t';
cout << endl;
}
}
~MyArray()
{
clearArray();
}
// clear memory and deinitialize pointers
void clearArray()
{
if (myArray == NULL)
return;
for (int i = 0; i < Variable1; ++i)
{
delete[] myArray[i];
myArray[i] = NULL;
}
delete[]myArray;
myArray = NULL;
}
};
int main(){
srand(time(0));
MyArray myArrayA;
myArrayA.displayMyArray();
cout << endl;
MyArray myArrayB;
myArrayB.displayMyArray();
cout << endl;
MyArray myArrayC(myArrayA, myArrayB);
myArrayC.displayMyArray();
getchar();
getchar();
return 0;
}
but I strongly recomend you to create proper copy constructor and assignment operator means (operator=) to proper object creation and destruction.
Here I post my own matrix realization to refer you in what way you can approve your code.
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
using namespace std::
class Matrix
{
public:
Matrix();
Matrix(int rowcount,int colcount);
Matrix(int rowcount,int colcount,float* matrix);
Matrix(const Matrix& rhs);
~Matrix();
/////////////////////////////////////////////////////////////
Matrix& operator = (const Matrix& rhs);
Matrix operator + (const Matrix& rhs);
Matrix operator - (const Matrix& rhs);
Matrix operator * (float scale);
Matrix operator * (const Matrix& rhs);
void operator += (const Matrix& rhs);
void operator -= (const Matrix& rhs);
void operator *= (float scale);
void operator *= (const Matrix& rhs);
float operator [] (int offset) const;
float& operator [] (int offset);
friend ostream& operator << (ostream& _str,const Matrix& rhs);
/////////////////////////////////////////////////////////////
void setCols(int cols);
void setRows(int rows);
void setMatrix(float* matrix);
int getCols() const
{
return itsCols;
}
int getRows() const
{
return itsRows;
}
const float* getMatrix() const
{
Invariants();
return itsMatrix;
}
void Invariants() const
{
if ((!(itsCols && itsRows && itsMatrix)) && (itsRows < 0) && (itsCols < 0))
{
cout << "Not allowed action!\n";
getch();
exit(0);
}
}
/////////////////////////////////////////////////////////////
private:
float* itsMatrix;
int itsRows;
int itsCols;
};
Matrix::Matrix()
{
itsRows = 0;
itsCols = 0;
itsMatrix = NULL;
}
Matrix::Matrix(int rowcount,int colcount)
{
itsRows = rowcount;
itsCols = colcount;
itsMatrix = new float[itsRows * itsCols];
Invariants();
}
Matrix::Matrix(int rowcount,int colcount,float* matrix)
{
itsRows = rowcount;
itsCols = colcount;
itsMatrix = new float[itsCols * itsRows];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = matrix[counter];
counter++;
}
}
Invariants();
}
Matrix::Matrix(const Matrix& rhs)
{
itsCols = rhs.getCols();
itsRows = rhs.getRows();
itsMatrix = new float[itsRows * itsCols];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = rhs[counter];
counter++;
}
}
}
Matrix::~Matrix()
{
itsCols = 0;
itsRows = 0;
delete [] itsMatrix;
itsMatrix = NULL;
}
Matrix& Matrix::operator = (const Matrix& rhs)
{
if (&rhs == this)
return *this;
else
{
itsRows = rhs.getRows();
itsCols = rhs.getCols();
delete [] itsMatrix;
itsMatrix = NULL;
itsMatrix = new float[itsRows * itsCols];
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
itsMatrix[counter] = rhs[counter];
counter++;
}
}
return *this;
}
}
float& Matrix::operator [] (int offset)
{
Invariants();
if ((offset > -1) && (offset < itsCols * itsRows))
return itsMatrix[offset];
else
{
cout << "You cann't reach this element!\n";
getch();
exit(0);
}
return itsMatrix[offset];
}
float Matrix::operator [] (int offset) const
{
Invariants();
if ((offset > -1) && (offset < itsCols * itsRows))
return itsMatrix[offset];
else
{
cout << "You cann't reach this element!\n";
getch();
exit(0);
}
return 0;
}
Matrix Matrix::operator + (const Matrix& rhs)
{
Invariants();
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform addiction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] + rhs[counter];
counter++;
}
}
return temp;
}
Matrix Matrix::operator - (const Matrix& rhs)
{
Invariants();
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform substraction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] - rhs[counter];
counter++;
}
}
return temp;
}
Matrix Matrix::operator * (float scale)
{
Invariants();
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] * scale;
counter++;
}
}
return temp;
}
Matrix Matrix::operator * (const Matrix& rhs)
{
Invariants();
if (!(itsCols == rhs.getRows()))
{
cout << "Cann't perform multiplication of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,rhs.getCols());
int counter = 0;
float sum = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
for (int k = 0; k < itsCols; k++)
{
sum += itsMatrix[i * itsCols + k] *
rhs[k * rhs.getCols() + j];
}
temp[counter] = sum;
sum = 0;
counter++;
}
}
return temp;
}
void Matrix::operator += (const Matrix& rhs)
{
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform addiction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] + rhs[counter];
counter++;
}
}
*this = temp;
}
void Matrix::operator -= (const Matrix& rhs)
{
if (!((this->itsCols == rhs.getCols()) &&
(this->itsRows == rhs.getRows())))
{
cout << "Cann't perform substraction of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] - rhs[counter];
counter++;
}
}
*this = temp;
}
void Matrix::operator *= (float scale)
{
Invariants();
Matrix temp(itsRows,itsCols);
int counter = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < itsCols; j++)
{
temp[counter] = itsMatrix[counter] * scale;
counter++;
}
}
*this = temp;
}
void Matrix::operator *= (const Matrix& rhs)
{
Invariants();
if (!(itsCols == rhs.getRows()))
{
cout << "Cann't perform multiplication of matrixes!\n";
getch();
exit(0);
}
Matrix temp(itsRows,rhs.getCols());
int counter = 0;
float sum = 0;
for (int i = 0; i < itsRows; i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
for (int k = 0; k < itsCols; k++)
{
sum += itsMatrix[i * itsCols + k] *
rhs[k * rhs.getCols() + j];
}
temp[counter] = sum;
sum = 0;
counter++;
}
}
*this = temp;
}
ostream& operator << (ostream& _str,const Matrix& rhs)
{
rhs.Invariants();
int counter = 0;
for (int i = 0; i < rhs.getRows(); i++)
{
for (int j = 0; j < rhs.getCols(); j++)
{
_str << rhs[counter] << "\t";
counter++;
}
_str << endl;
}
return _str;
}
float arr1[] =
{
2, 2, 2,
-1, -3, -5,
16, 8, 24,
8, 0, 16
};
float arr2[] =
{
15,
2,
-4
};
int main()
{
clrscr();
Matrix m1(4,3,arr1);
Matrix m2(3,1,arr2);
cout << "Matrix 1:\n";
cout << m1 << endl;
cout << "Matrix 2:\n";
cout << m2 << endl;
cout << "Matrix 1 * Matrix 2\n";
cout << m1 * m2 << endl;
getch();
cout << "Matrix 1 + Matrix 1\n";
cout << m1 + m1 << endl;
getch();
cout << "Matrix 1 - Matrix 1\n";
cout << m1 - m1 << endl;
getch();
cout << "Matrix 1 * 4\n";
cout << m1 * 4 << endl;
getch();
return 0;
}