Saturday, April 28, 2012

8.31

Write a polymorphic max function in C++ that takes an array of values of any type and returns the maximum value in the array, assuming the existence of a ">" operation


#include <iostream>
using namespace std;


template <typename T>
T max(T x[], int size)
{
T max x[0];
for(int i=0; i<size;i++)
{
max = (x[i]>max)?x[i]:max;
}
return max;
}


template <typename T>
T max(T x[], int size, bool (*gt)(T,T))
{
T max = x[0];
for(int i=1;i<size;i++)
{
max = (*gt)(x[i],max)?x[i]:max;
}
return max;
}


int main()
{
char temparray[4] = {'a','c','f','d'};
cout << max(temparray, 4);
system("Pause");
return 0;
}

No comments:

Post a Comment