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
|
Write a template function maxn() that takes as its arguments an array of items of
type T and an integer representing the number of elements in the array and that
returns the largest item in the array. Test it in a program that uses the function
template with an array of six int values and an array of four double values.
The program should also include a specialisation that takes an array of pointer-to-char as
an argument and the number of pointers as a second argument and that returns address
of the longest string. If multiple strings are tied for having the longest length,
the function should return the address of the first one tied for longest.
Test the specialisation with an array of five string pointers.
*/
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
T maxn(T *x, int n);
template <> const char * maxn(const char * pc[], int n);
int main()
{
const int inum = 6;
const int dnum = 4;
int intar[inum] = { 1, 2, 3, 12, 5, 6 };
double doublar[dnum]{ 1.0, 6.45, 3.0, 4.0 };
cout << "The biggest value of intar: " << maxn(intar, inum) << endl;
cout << "The biggest value of doublar: " << maxn(doublar, dnum) << endl;
const int pcnum = 5;
const char * pc[pcnum] =
{
"One", "This is two", "And this is three", "And this definitely
must be four", " This is five"
};
cout << "The longest string is: " << maxn(pc, pcnum) << endl;
system("pause");
return 0;
}
template <typename T>
T maxn(T *x, int n)
{
T max = 0;
for (int i = 0; i < n; i++)
{
max = x[i] > max ? x[i] : max;
}
return max;
}
template <> const char * maxn(const char * pc[], int n)
{
int max = 0;
for (int i = 0; i < (n - 1); i++)
{
max = strlen(pc[i]) >= strlen(pc[i + 1]) ? i : max;
}
return pc[max];
}
|