Question

Need C++ coding for this lab exercise given below :) 4. Lab Exercise — Templates Exercise...

Need C++ coding for this lab exercise given below :)

4. Lab Exercise — Templates


Exercise 1 - Function Templating


For this part of the lab make a template out of the myMax function and test it on different data types.

Copy maxTemplate.cpp to your Hercules account space. Do that by:


Entering the command:cp /net/data/ftp/pub/class/115/ftp/cpp/Templates/maxTemplate.cpp maxTemplate.cpp


Compile and run the program to see how it works.


Make a template out of myMax. Don't forget the return type.


Modify the prototype appropriately.


Test your myMax template on int, double, and string types.


When you are done your output should resemble this:The max of 3 and 5 is 5 The max of 5.6 and 7.3 is 7.3 The max of donkey and apple is donkey

Exercise 2 - Class Templating


For this part of the lab you will make a template out of the Matrix class, test it on different data types, and add a generic sort member function.

Transfer matrix.cppmatrix.htempMain.cpp, andMakefile your lab directory. Do that by changing into your directory and:


Entering these commands:cp /net/data/ftp/pub/class/115/ftp/cpp/Templates/matrix.cpp matrix.cpp cp /net/data/ftp/pub/class/115/ftp/cpp/Templates/matrix.h matrix.h cp /net/data/ftp/pub/class/115/ftp/cpp/Templates/tempMain.cpp tempMain.cpp cp /net/data/ftp/pub/class/115/ftp/cpp/Templates/Makefile Makefile


Part 1: Setup


Add the template types to matrix.cpp


Template the definition of the Matrix class in matrix.h.


Template the member functions in matrix.cpp.
Hint: You may find Emacs query-replace M-%, cut line C-a C-k C-k and paste C-y helpful.


The Makefile is set up for you. Use it to compile and run the program to make sure everything is working.


Part 2: Extend


Add two more 2D arrays to tempMain.cpp that hold a new data type.


Create an instances of Matrix that can hold that data type and use the templated demoTemplate function to show that your templated class works.


Test your changes.


Your completed exercise should resemble this:

Demonstrating with string matrix: Matrix set to first array Congra y ar alm don La Matrix incremented by second array Congratulations you are almost done the Lab! Demonstrating with int matrix: Matrix set to first array 1 2 3 4 5 6 Matrix incremented by second array 7 7 7 7 7 7 Demonstrating with float matrix: Matrix set to first array 1.6 2.5 3.4 4.3 5.2 6.1 Matrix incremented by second array 7.7 7.7 7.7 7.7 7.7 7.7

maxTemplate.cpp

/**************************************************** * * FileName: /net/data/ftp/pub/class/170/ftp/cpp/maxTemplate.cpp * Purpose: Demonstrate the use of function templates * ********************************************************/ #include <iostream> #include <string>
using namespace std;
//Make a template out of the prototype int myMax(int one, int two);
int main() {
int i_one = 3, i_two = 5;
cout << "The max of " << i_one << " and " << i_two << " is " << myMax(i_one, i_two) << endl; //Test your template on float and string types
return 0;
}
//Make a template out of this function. Don't forget the return type. int myMax(int one, int two) { int biggest; if (one < two) { biggest = two; } else { biggest = one; } return biggest;
}

matrix.cpp
#include "matrix.h"
#include <iostream>
using namespace std;
Matrix::Matrix() {
rows = MAXROWS; cols = MAXCOLS;
for (int i=0; i< rows; i++) {
for(int j=0; j< cols; j++) {
doubleArray[i][j] = '\0'; } } } void Matrix::printMatrix()
{
for (int i=0; i< rows; i++)
{ for(int j=0; j< cols; j++) {
cout << doubleArray[i][j] << " "; }
cout << endl;
}
}
void Matrix::setMatrix(int otherArray[][MAXCOLS]) {
for (int i=0; i< rows; i++)
{ for(int j=0; j< cols; j++) {
doubleArray[i][j] = otherArray[i][j];
}
}
}
void Matrix::addMatrix(int otherArray[][MAXCOLS])
{
for (int i=0; i< rows; i++)
{
for(int j=0; j< cols; j++)
{
doubleArray[i][j] += otherArray[i][j];
}
}
} void Matrix::addMatrix(Matrix otherMatrix) { addMatrix(otherMatrix.doubleArray);
}

matrix.h

const int MAXROWS=2;
const int MAXCOLS=3;
class Matrix
{
private: int doubleArray[MAXROWS][MAXCOLS];
int rows;
int cols;
public: //Constructor Matrix();
//Set rows to MAXROWS and cols to MAXCOLS
//Initialize all the values of doubleArray to zero
//Getter Functions void printMatrix();
//Setter Functions void setMatrix(int [][MAXCOLS]);
//set the doubleArray to what is sent void addMatrix(int [][MAXCOLS]);
//add an array to doubleArray void addMatrix(Matrix otherMatrix);
//No destructor needed
};

tempMain.cpp

#include <iostream>
#include <string>
#include "matrix.h"
using namespace std;
template <typename T1> void demoTemplate(Matrix<T1>& M, T1 array1[][MAXCOLS], T1 array2[][MAXCOLS]);
int main()
{
string str1[MAXROWS][MAXCOLS] = { {"Congra", "y", "ar"}, {"alm", "don", "La"} }; string str2[MAXROWS][MAXCOLS] = { {"tulations", "ou", "e"}, {"ost", "e the", "b!"} }; int num1[MAXROWS][MAXCOLS] = { {1,2,3}, {4,5,6} };
int num2[MAXROWS][MAXCOLS] = { {6,5,4}, {3,2,1} };
Matrix<string> stringMatrix;
Matrix<int> intMatrix;
cout << "\nDemonstrating with string matrix:" << endl; demoTemplate(stringMatrix, str1, str2); cout << "\nDemonstrating with int matrix:" << endl;
demoTemplate(intMatrix, num1, num2); cout << "\n" << endl;
return 0;
}
template <typename T1> void demoTemplate(Matrix<T1>& M, T1 array1[][MAXCOLS], T1 array2[][MAXCOLS]) { M.setMatrix(array1);
cout << "\nMatrix set to first array" << endl;
M.printMatrix();
M.addMatrix(array2);
cout << "\nMatrix incremented by second array" << endl;
M.printMatrix();
}

Makefile

COMPILER = g++ # or CC if you prefer it on Hercules
DRIVER = tempMain
FILE = matrix
$(DRIVER) : $(FILE).o $(DRIVER).o #the first character on the next line is a tab
$(COMPILER) -o $(DRIVER) $(FILE).o
$(DRIVER).o
$(DRIVER).o : $(DRIVER).cpp $(FILE).cpp $(FILE).h
$(COMPILER) -c $(DRIVER).cpp -o
$(DRIVER).o
$(FILE).o : $(FILE).cpp $(FILE).h $(COMPILER) -c $(FILE).cpp -o
$(FILE).o
clean: @ /bin/rm -f *.o

template types

Overview:


If you try to define templates in multiple files, it is likely that you will come across a linker error in Visual C++. The error might be something like the following:error LNK2019: unresolved external symbol "public: __thiscall my_class ::my_class(int,int)" (??0?$my_class@H@@QAE@HH@Z)


To get rid of this error, you need to add the following at the end of .cpp file, so at the end of the swapper.cpp, add the following:template class my_class <int>; template class my_class <char>; template class my_class <double>;


Complete comments which are needed in the lab exercise for the correct output.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code Implemented in C++

Note: Comments are written for code explanation

Filename: maxTemplate.cpp

/****************************************************
*
* FileName: /net/data/ftp/pub/class/170/ftp/cpp/maxTemplate.cpp
* Purpose: Demonstrate the use of function templates
*
********************************************************/
#include <iostream>
#include <string>
using namespace std;

template <class T>//Make a template out of the prototype
T myMax(T one, T two);

int main()
{
int i_one = 3, i_two = 5;
double d_one = 5.6, d_two = 7.3;
string s_one = "donkey", s_two = "apple";

cout << "The max of " << i_one << " and " << i_two << " is "
   << myMax(i_one, i_two) << endl;

//Test your template on float and string types
cout << "The max of " << d_one << " and " << d_two << " is "
   << myMax(d_one, d_two) << endl;

cout << "The max of " << s_one << " and " << s_two << " is "
   << myMax(s_one, s_two) << endl;
  
return 0;
}


template <class T>//Make a template out of this function. Don't forget the return type.
T myMax(T one, T two)
{
T bigger;
if (one < two)
{
bigger = two;
}
else
{
bigger = one;
}
return bigger;
}

Filename: matrix.cpp

#ifndef __MATRIX_CPP__
#define __MATRIX_CPP__
#include "matrix.h"
#include <iostream>
using namespace std;
template <class M_type>
Matrix<M_type>::Matrix()
{
rows = MAXROWS;
cols = MAXCOLS;
for (int i=0; i< rows; i++)
{
for(int j=0; j< cols; j++)
{
   doubleArray[i][j] = '\0';
}
}
}   
template <class M_type>
void Matrix<M_type>::printMatrix()
{
for (int i=0; i< rows; i++)
{
for(int j=0; j< cols; j++)
{
   cout << doubleArray[i][j] << " ";
}
cout << endl;
}
}
template <class M_type>
void Matrix<M_type>::setMatrix(M_type otherArray[][MAXCOLS])
{
for (int i=0; i< rows; i++)
{
for(int j=0; j< cols; j++)
{
   doubleArray[i][j] = otherArray[i][j];
}
}
}
template <class M_type>
void Matrix<M_type>::addMatrix(M_type otherArray[][MAXCOLS])
{
for (int i=0; i< rows; i++)
{
for(int j=0; j< cols; j++)
{
   doubleArray[i][j] += otherArray[i][j];
}
}
}
template <class M_type>
void Matrix<M_type>::addMatrix(Matrix otherMatrix)
{
addMatrix(otherMatrix.doubleArray);
}
#endif

Filename: matrix.h

#ifndef __MATRIX_H__
#define __MATRIX_H__

const int MAXROWS=2;
const int MAXCOLS=3;

template <class M_type>
class Matrix
{
private:
M_type doubleArray[MAXROWS][MAXCOLS];
int rows;
int cols;

public:
//Constructor
Matrix(); //Set rows to MAXROWS and cols to MAXCOLS
   //Initialize all the values of doubleArray to zero
  
//Getter Functions
void printMatrix();

//Setter Functions
void setMatrix(M_type [][MAXCOLS]); //set the doubleArray to what is sent
void addMatrix(M_type [][MAXCOLS]); //add an array to doubleArray
void addMatrix(Matrix otherMatrix);

//No destructor needed
};

#endif
#include "matrix.cpp"

Filename: tempMain.cpp

#include <iostream>
#include <string>
#include "matrix.h"

using namespace std;

template <class T1>
void demoTemplate(Matrix<T1>& M, T1 array1[][MAXCOLS], T1 array2[][MAXCOLS]);

int main()
{
string Str1[MAXROWS][MAXCOLS] =
{
   {"Congra", "y", "ar"},
   {"alm", "don", "La"}
};
string Str2[MAXROWS][MAXCOLS] =
{
   {"tulations", "ou", "e"},
   {"ost", "e the", "b!"}
};
int Num1[MAXROWS][MAXCOLS] =
{
   {1,2,3},
   {4,5,6}
};
int Num2[MAXROWS][MAXCOLS] =
{
   {6,5,4},
   {3,2,1}
};

double d1[MAXROWS][MAXCOLS] =
{
{1.5, 2.5, 3.4},
{4.3, 5.2, 6.1}
};
double d2[MAXROWS][MAXCOLS] =
{
{6.2, 5.2, 4.3},
{3.4, 2.5, 1.6}
};

Matrix<string> stringMatrix;
Matrix<int> intMatrix;
Matrix<double> doubleMatrix;
cout << "\nDemonstrating with string matrix:" << endl;
demoTemplate(stringMatrix, Str1, Str2);
cout << "\nDemonstrating with int matrix:" << endl;
demoTemplate(intMatrix, Num1, Num2);
cout << "\nDemonstrating with float matrix:" << endl;
demoTemplate(doubleMatrix, d1, d2);

cout << "\n" << endl;
return 0;
}
template <class T1>
void demoTemplate(Matrix<T1>& M, T1 array1[][MAXCOLS], T1 array2[][MAXCOLS])
{
M.setMatrix(array1);
cout << "\nMatrix set to first array" << endl;
M.printMatrix();
M.addMatrix(array2);
cout << "\nMatrix incremented by second array" << endl;
M.printMatrix();
}

Filename: Makefile

COMPILER = g++ # or CC if you prefer it on Hercules

DRIVER = tempMain

FILE = matrix

$(DRIVER) : $(FILE).o $(DRIVER).o #the first character on the next line is a tab
   $(COMPILER) -o $(DRIVER) $(FILE).o $(DRIVER).o

$(DRIVER).o : $(DRIVER).cpp $(FILE).cpp $(FILE).h
   $(COMPILER) -c $(DRIVER).cpp -o $(DRIVER).o

$(FILE).o : $(FILE).cpp $(FILE).h
   $(COMPILER) -c $(FILE).cpp -o $(FILE).o

clean:
   @ /bin/rm -f *.o

Working code output screenshot:

If you like my answer, hit thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
Need C++ coding for this lab exercise given below :) 4. Lab Exercise — Templates Exercise...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help modifying this program. How would I make sure that the methods is being...

    I need help modifying this program. How would I make sure that the methods is being called and checked in my main method? Here is what the program needs to run as: GDVEGTA GVCEKST The LCS has length 4 The LCS is GVET This is the error that I'm getting: The LCS has length 4 // I got this right The LCS is   //the backtrace is not being called for some reason c++ code: the cpp class: /** * calculate...

  • This program is in C++ which reserves flight seats. It uses a file imported to get...

    This program is in C++ which reserves flight seats. It uses a file imported to get the seat chart called "chartIn.txt" which looks like this 1 A B C D E F 2 A B C D E F It continues until row 10. Sorry unable to provide the chartIn.txt file. I am having issues with function displaySeats, it displays then but when it comes to 10 the row looks like this 1 0 A B C D E ,...

  • Program is in C++, program is called airplane reservation. It is suppose to display a screen...

    Program is in C++, program is called airplane reservation. It is suppose to display a screen of seating chart in the format 1 A B C D E F through 10. I had a hard time giving the seats a letter value. It displays a correct screen but when I reserve a new seat the string seats[][] doesn't update to having a X for that seat. Also there is a file for the struct called systemUser.txt it has 4 users...

  • Submissions) Part A Type and run the Array class template discussed in lecture (Templates notes). Modify...

    Submissions) Part A Type and run the Array class template discussed in lecture (Templates notes). Modify the class by adding sort member function (refer to Algorithm Analysis notes for sorting algorithms) Sample usage: a. sort(); Add the needed code in main to test your function. template <class T> 1/you can use keyword typename instead of class class Array { private: T *ptr; int size; public: Array(T arr[], int s); void print(); template <class T> Array<T>:: Array (T arr[], int s)...

  • Directions: Develop a C++ program that can solve any matrix, up to 15 equations with 15...

    Directions: Develop a C++ program that can solve any matrix, up to 15 equations with 15 unknowns. Put the result on the screen as well as write the results to a text file This is what we were given as a hint: /* how to read matrix data file in rows and colloms written by tom tucker 03/26/2018 it uses a string array to read in the first line and then a nested for statement to read in the matrix...

  • C++ how can I fix these errors this is my code main.cpp #include "SpecialArray.h" #include <...

    C++ how can I fix these errors this is my code main.cpp #include "SpecialArray.h" #include <iostream> #include <fstream> #include <string> using namespace std; int measureElementsPerLine(ifstream& inFile) {    // Add your code here.    string line;    getline(inFile, line);    int sp = 0;    for (int i = 0; i < line.size(); i++)    {        if (line[i] == ' ')            sp++;    }    sp++;    return sp; } int measureLines(ifstream& inFile) {    // Add your code here.    string line;    int n = 0;    while (!inFile.eof())    {        getline(inFile,...

  • Study the c++ code below and answer the question on templates after // A polymorphic swap...

    Study the c++ code below and answer the question on templates after // A polymorphic swap function for any type of object (an example) template<typename T> void MySwap( T& x, T& y) { T temp; temp = x; x = y; y = temp; } // A polymorphic class holding an [x,y] position of any type template<class T> class Position { public: Position(T x=0, T y=0) : x_(x), y_(y) {} friend std::ostream& operator<<(std::ostream& os, const Position& p) { return os...

  • How do I compile c++ code in terminal. Below i have some code to apply Gaussian...

    How do I compile c++ code in terminal. Below i have some code to apply Gaussian Filter on an image using OpenCV. I have tried compling using the code g++ Project2.cpp -o Project2 `pkg-config --cflags --libs opencv` && ./Project2 and it gives me a whole list of errors saying directory not found. --------------------------------------------------------------------------------------------------------- #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <opencv2/core/core.hpp> #include <iostream> using namespace cv; using namespace std; int main() { Mat image = imread("//u//oowens//First.jpg"); int rows=image.rows; int cols=image.cols; if (image.empty())...

  • C++ assignment help! The instructions are below, i included the main driver, i just need help...

    C++ assignment help! The instructions are below, i included the main driver, i just need help with calling the functions in the main function This assignment will access your skills using C++ strings and dynamic arrays. After completing this assignment you will be able to do the following: (1) allocate memory dynamically, (2) implement a default constructor, (3) insert and remove an item from an unsorted dynamic array of strings, (4) use the string class member functions, (5) implement a...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT