64,653
社区成员
发帖
与我相关
我的任务
分享
// ex6, ch 8
#include <iostream>
#include <cstring>
template <typename T>
T ret_max(T [], int);
template <> char * ret_max(char *[], int);
int main()
{
using namespace std;
int ar_int[6] = {3, 7, 2, 5, 6, 4};
double ar_doub[4] = {2.1, 3.4, 1.8, 4.2};
char * str[5] = {
"I really can't understand you.",
"You're my dearest baby.",
"How much do you love me?",
"I really can't understand you.",
"I really can't understand you."
};
char * s;
cout << "Max of the six integers: " << ret_max(ar_int, 6) << endl;;
cout << "Max of the four integers: " << ret_max(ar_doub, 4) << endl;
cout << "The five strings and their addresses:" << endl;
for (int i = 0; i < 5; i++)
{
cout << str[i] << endl;
cout << (unsigned)str[i] << endl;
}
cout << "The largest of the five and its address:" << endl;
s = ret_max(str, 5);
cout << s << endl;
cout << (unsigned)s << endl; // 用unsigned打印指针内容,请还有其他打印法可以显示0x进制的模式吗?
return 0;
}
template <typename T>
T ret_max(T ar[], int n)
{
T max = ar[0];
for(int i = 0; i < n; i++)
if(max < ar[i])
max = ar[i];
return max;
}
template <> char * ret_max(char * str[], int n)
{
int i, max = 0;
for(i = 0; i < n; i++)
if(strlen(str[max]) < strlen(str[i]))
max = i;
return str[max];
}