1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
#include <stdio.h>
#include <stdlib.h>
#include <new>
using namespace std;
class matrix {
int row;
int col;
int **array;
public:
matrix(int,int); //constuctor
matrix(const matrix&); //constructor to copy a matrix
~matrix(); //destructor
void setElement(int r, int c, int e);
int getElement (int r, int c);
void setColumn (int c, int a[]);
int* getColumn (int c);
void setRow (int r, int a[]);
int* getRow (int r);
matrix operator+(const matrix&);
};
matrix::matrix(int r, int c){ //defines the constructor to create a new matrix
row = r;
col = c;
array = new int*[row];
for (int i=0; i<row; i++){
array[i] = new int[col];
}
for (int i=0; i<row; i++){
for (int j=0; j<col; j++){
array[i][j] = 0;
}
}
};
matrix::matrix(const matrix& m){ //defines the copying constructor
row = m.row;
col = m.col;
array = new int*[row];
for (int i=0; i<row; i++){
array[i] = new int[col];
}
for (int i=0; i<row; i++){
for (int j=0; j<col; j++){
array[i][j] = m.array[i][j];
}
}
}
matrix::~matrix(){ //defines the destructor
for (int i=0; i<row; i++){
delete[] array[i];
}
delete[] array;
};
void matrix::setElement(int r, int c, int e){
array[r][c] = e;
};
int matrix::getElement(int r, int c){
return array[r][c];
}
void matrix::setColumn(int c, int a[]){
for (int i=0; i<row; i++){
array [i][c] = a[i];
}
}
int* matrix::getColumn(int c){
int *output = new int[row];
for (int i=0; i<row; i++){
output[i] = array[i][c];
}
return output;
}
void matrix::setRow(int r, int a[]){
for(int i=0; i<col; i++){
array[r][i] = a[i];
}
}
int* matrix::getRow (int r){
int *output = new int[col];
for (int i=0; i<col; i++){
output[i] = array[r][i];
}
return output;
}
matrix matrix::operator+(const matrix& m){
// first, make sure matrices can be added. if not, return original matrix
if (row != m.row || col != m.col){
cerr << "Matrix sizes do not match. Mission impossible.";
return (*this);
}
matrix new_mat(row,col);
for (int i=0; i<row; i++){
for (int j=0; j<col; j++){
new_mat.array[i][j] = array[i][j] + m.array[i][j];
}
}
return new_mat;
}
|