您的位置:首页 > 编程语言 > C语言/C++

C++ Primer Plus第六版编程练习8.6解答

2015-03-27 23:03 489 查看
ps:这题的具体化函数实现博主用了两种方法。

方法一:使用strcmp

/***************

具体化函数思路:
比较字符串大小可以用strcmp函数,而考虑到strcmp函数
比较字符串大小时是按ASCII码顺序比较的,也就是说大写
字母会比小写字母小,譬如:字符串"Hello"比字符串"hello"小,
可这显然不是我们想要的结果,我们想要的结果是字符串"Hello"
与字符串"hello"大小相等。于是我先创建一个包含5个元素的
字符串数组,把函数调用时传进来的字符串复制到这个数组
然后把这些字符串全部替换为小写的形式,再对它们进行比较,
这样就能得到想要的结果了。

PS:要创建数组来存放复制的字符串的原因:
如果用了char *p="Hello"来定义字符串,其实这样定义的字符串
是相当于const char *p="Hello"的,也就是说不能修改里面的值。
所以不能把它里面的大写改为小写,于是要用char str[StrSize]
来存放复制的结果,才可以修改里面每个字符。

***************/

#include
#include   //for strcmp, strcpy, strlen

const int StrSize=20;

//模板函数声明
template
T maxn(T a[],int n);

//具体化函数声明
template <> char * maxn(char *s[],int n);

int main(void)
{
int arr_i[6]= {23,35,344,643,235,34};
std::cout<<"int type\n";
std::cout<<"The max number is "<
T maxn(T a[],int n)
{
T max=a[0];
for(int i=1; imax)
max=a[i];
}
return max;
}

//具体化函数的定义
template <> char * maxn(char *s[],int n)
{
char tempStr[5][StrSize]= {'\0'};  //定义了5个字符串数组,每个的大小为StrSize

//先把5个字符串形参复制到tempStr数组
int i,j;
for(i=0; i0)
{
num=i;
strcpy(MaxStr,tempStr[i]);
}
}

return s[num];  //返回最大的字符串
}


方法二:对每个字符串的字符进行逐个比较

/***************

具体化函数思路:
不用strcmp函数,而是用循环逐个字符进行比较。当然
这也会遇到第一种方法里提到的大小写的ASCII码顺序的
问题,这时候可以用cctype里的tolower或toupper函数来解决。

***************/

#include
#include   //for strlen
#include

const int StrSize=20;

//模板函数声明
template
T maxn(T a[],int n);

//具体化函数声明
template <> char * maxn(char *s[],int n);

int main(void)
{
int arr_i[6]= {23,35,344,643,235,34};
std::cout<<"int type\n";
std::cout<<"The max number is "<
T maxn(T a[],int n)
{
T max=a[0];
for(int i=1; imax)
max=a[i];
}
return max;
}

//具体化函数的定义
template <> char * maxn(char *s[],int n)
{
char ch_m,ch;
int max=0;  //max存储最大的字符串的编号
int i,j;
for(i=1; itolower(ch_m))  //每个字符串里有大写也有小写
{
max=i;
break;
}
else
break;
}
}

return s[max];
}


总结:

对比这两种方法,使用第二种比较节省空间,因为不用修改实参的字符串内容,所以不用另外开辟存储空间。这要得益于cctpye里的tolower函数,它可以返回大写字符对应的小写,然后我们再进行比较就可以得到想要的结果了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: