11.5k views
2 votes
You are asked to implement two function templates and a class template. findMax() function template Complete the definition of a function template, named find Max(), which takes the input of an array of any data type and an integer that tells the number of elements in the given array. This function will return the maximum element (with the maximum value) in the given array. MyPair class template Complete the definition of a class template, named MyPair. This template class consists of two private member variables, left and right that may or may not be the same type. For instance, you can use?

1 Answer

3 votes

Answer:

see explaination

Step-by-step explanation:

//templateFunctions.h file

#ifndef TEMPLATEFUNCTIONS_H

#define TEMPLATEFUNCTIONS_H

#include <iostream>

using namespace std;

#include "templateClass.h"

//FIX ME: Complete the header of the function template findMax()

// This function takes the array of any type as input and return its maximum value

template <typename T>

T findMax(const T arr[], int nelems)

{

T max = arr[0];

for (int i = 1; i < nelems; i++)

{

if (arr[i] > max)

max = arr[i];

}

return max;

}

//

// FIX ME: Implement the swapPairObjs() function that swaps the two objects of MyPair

template<typename T1, typename T2>

void swapPairObjs(MyPair<T1,T2>& object1, MyPair<T1,T2>& object2)

{

T1 temp1_left=object1.getLeft(),temp2_left=object2.getLeft();

T2 temp1_right=object1.getRight(),temp2_right=object2.getRight();

object1.setLeft(temp2_left);

object2.setLeft(temp1_left);

object1.setRight(temp2_right);

object2.setRight(temp1_right);

}

#endif

//templateClass.h file

#ifndef MYPAIR_H

#define MYPAIR_H

// FIX ME: please provide the proper template prefix for the MyPair class template

template <typename T1, typename T2>

class MyPair {

public:

MyPair(T1 _left, T2 _right);

T1 getLeft();

T2 getRight();

void setLeft(T1 _left);

void setRight(T2 _right);

private:

T1 left;

T2 right;

};

//FIX ME: Complete the definition of the constructor MyPair(T1 _left, T2 _right)

// that will assign value _left to the left variable and _right to right.

template<typename T1, typename T2>

MyPair<T1,T2>::MyPair(T1 _left, T2 _right)

{

left=_left;

right=_right;

}

//FIX ME: Complete the definition of the getLeft() function

template<typename T1, typename T2>

T1 MyPair<T1,T2>::getLeft()

{

return left;

}

//FIX ME: Complete the definition of the setLeft() function

template<typename T1, typename T2>

void MyPair<T1,T2>::setLeft(T1 _left)

{

left=_left;

}

//FIX ME: Complete the definition of the getRight() function

template<typename T1, typename T2>

T2 MyPair<T1,T2>::getRight()

{

return right;

}

//FIX ME: Complete the definition of the setRight() function

template<typename T1, typename T2>

void MyPair<T1,T2>::setRight(T2 _right)

{

right=_right;

}

#endif // !MYPAIR_H

User Ze
by
3.8k points