Hello, this question was on my midterm and my instructor wasn't nice enough to provide an answer key. I am having quite the difficulty of getting this to work.
I'm suppose to do as followed :
Define a Class Matrix (integer matrix) with
1.A Default constructor.
2.A constructor that takes as parameters number of rows m and columns n of the matrix. it should dynamically allocate the 2-dimensional array to hold m x n integers.
3.A method to set the value of the (i,j)th-entry of the matrix to a given integer.
4.A method to display the matrix.
5.The Destructor
6.Write a driver (main program) to create a 4x3 matrix and initialize it by reading the entries from the keyboard. Further, display the matrix by calling your "display" method.
I can omit the Assignment = operator.
I'm quite lost on how to create my set value method and was hoping for some insight on where to begin. Also if the rest of my code is okay.
My code so far :
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
|
#include <iostream>
#include <cstdlib>
using namespace std;
class Matrix
{
public:
Matrix(); //Default constructor
Matrix(int m, int n); //Main constructor
void setVal(int m, int n); //Method to set the val of [i,j]th-entry
void printMatrix(); //Method to display the matrix
~Matrix(); //Destructor
private:
int m, n;
int **p;
//allocate the array
void allocArray()
{
p = new int*[m];
for(int i = 0; i < m; i++)
{
p[i] = new int[n];
}
}
};
//Default constructor
Matrix::Matrix() : Matrix(1,1) {}
//Main construcor
Matrix::Matrix(int m, int n)
{
allocArray();
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
p[i][j] = 0;
}
}
}
//destructor
Matrix::~Matrix()
{
for(int i = 0; i < m; i++)
{
delete [] p[i];
}
delete [] p;
}
//SetVal function
void Matrix::setVal(int m, int n)
{
int newVal = 0;
p[m][n] = newVal;
}
//printMatrix function
void Matrix::printMatrix()
{
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
cout << p[m][n] << " " << endl;
}
}
}
int main()
{
int d1 = 4;
int d2 = 3;
Matrix object;
//create 4x3 dynamic 2d array
int ** matrix = new int*[d1];
for(int j = 0; j < d1; j++)
{
matrix[j] = new int[d2];
}
//fill array
cout << "Enter values " << endl;
for(int i = 0; i < d1; ++i)
{
for(int j = 0; j < d2; ++j)
{
cin >> matrix[i][j];
}
}
object.printMatrix();
return 0;
}
|
Help is very much appreciated.