C++ ONLY!! Exercise 1: Chapter 11, Postlab Exercise 8 asked you to implement a m
ID: 3719979 • Letter: C
Question
C++ ONLY!! Exercise 1: Chapter 11, Postlab Exercise 8 asked you to implement a matrix with the following functions for a 5-by-4 matrix. Rewrite this program as a template class,where the template argument is either an int or a float. ADD - Takes two matrices (A and B) as input and returns a matrix (Result) in which each position is the sum of the corresponding positions in A and B. SUB - Takes two matrices (A and B) as input and returns a matrix (Result) in which each position is the corresponding position in A minus the corresponding position in B. WRITE - Takes a file name and a matrix as input and writes the matrix by row, one row per line on the file. GetMat - Takes a file name and a matrix as input, reads values from the file, and stores those values into the matrix. Rewrite your solution by overloading the arithmetic operators for plus and minus. Can you use the same test plan you used for the previous version? Explain.
Explanation / Answer
template<class T>
T **ADD(T a[][4], T b[][4]){
T **p = new T*[5];
for (int i = 0; i<5; i++){
p[i] = newT[4];
}
for (int i = 0; i<5; i++){
for (int j = 0;j<4; j++){
p[i][j] = a[i][j] + b[i][j];
}
}
return p;
}
template<class T>
T **SUB(T a[][4], T b[][4]){
T **p = new T*[5];
for (int i = 0; i<5; i++){
p[i] = newT[4];
}
for (int i = 0; i<5; i++){
for (int j = 0;j<4; j++){
p[i][j] = a[i][j] - b[i][j];
}
}
return p;
}
template<class T>
void WRITE(T a[][4], string nm){
ofstream fout(nm.c_str());
for (int i = 0; i<5; i++){
for (int j = 0;j<4; j++){
fout << a[i][j] << " ";
}
fout <<endl;
}
fout.close();
}
template<class T>
void GetMat(T &a[][4], string nm){
ifstream fin(nm.c_str());
if (!fin){
cout <<"Error opening filr ";
return 0;
}
for (int i = 0; i<5;i++){
for (int j = 0;j<4; j++){
fin >> a[i][j];
}
}
fin.close();
}
//Overoading Airthmatic operators
T **operator +(const T &a[][4], const T &b[][4]){
T **p = new T*[5];
for (int i = 0; i<5; i++){
p[i] = newT[4];
}
for (int i = 0; i<5; i++){
for (int j = 0;j<4; j++){
p[i][j] = a[i][j] + b[i][j];
}
}
return p;
}
template<class T>
T **operator -(const T &a[][4], const T &b[][4]){
T **p = new T*[5];
for (int i = 0; i<5; i++){
p[i] = newT[4];
}
for (int i = 0; i<5; i++){
for (int j = 0;j<4; j++){
p[i][j] = a[i][j] - b[i][j];
}
}
return p;
}
Yes we can use the same test plan as earlier
Please give Thumbs up,if it helped you :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.