|
发表于 2017-12-15 21:11:10
|
显示全部楼层
#include <string.h>
#include <iostream>
using namespace std;
template<class T>
inline const T& maxn(const T *arr, int n)
{
// assert(n > 0);
int maxIndex = 0;
int i = 0; // init i=0 just for code style, not a use value
for (i = 1; i < n; ++i)
{
if (arr[maxIndex] < arr[i]) maxIndex = i;
}
return arr[maxIndex];
}
typedef char* PChar;
template<>
inline const PChar& maxn(const PChar *arr, int n)
{
// assert(n > 0);
int maxIndex = 0;
int i = 0; // init i=0 just for code style, not a use value
for (i = 1; i < n; ++i)
{
if ( strlen(arr[maxIndex]) < strlen(arr[i]) ) maxIndex = i;
}
return arr[maxIndex];
}
void Test_maxn()
{
#define dim(arr) ( sizeof(arr)/sizeof(*arr) )
int iarr[] = {6, 5, 3, 2, 1, 4};
cout<<maxn(iarr, dim(iarr))<<endl;
double darr[] = {2.0, 1.0, 4.0, 3.0};
cout<<maxn(darr, dim(darr))<<endl;
PChar strArr[] = {"one", "two", "three", "hello", "five"};
cout<<maxn<PChar>(strArr, dim(strArr))<<endl;
}
|
|