请编写一个函数maxofarray(atype*p int count) 该函数从一个数组中
问题详情
请编写一个函数maxofarray(atype*p,int count),该函数从一个数组中找出其中的最大元素,并且数组中可以存放多种数据类型的元素。
注意:部分源程序己存在文件test42_2.cpp中。
请勿修改主函数main和其他函数中的任何内容,仅在函数maxofarray的花括号中填写若干语句。
文件test42_2.cpp清单如下:
include<iostream.h>
include<string.h>
include<conio.h>
template<class atype>
void maxofarray(atype* p,int count)
{
}
void main ()
{
int len=5;
char *p1;
cout<<"the char type array and it"s length is 5:n";
cout<<"the array element is a b c d en";
p1=new char[len];
for (int i=0;i<len;i++)
p1[i]="a"+i;
maxofarray(p1,len);
}请帮忙给出正确答案和分析,谢谢!
参考答案
正确答案:void maxofarray(atype*pint count){for (int j=0;j<count-1;j++){for (int k=0;k<count-1-j;k++)if(p[k]>p[k+1]){atype temp;temp=p[k];p[k]=p[k+1];p[k+1]=temp;}}cout<<"\nthe max element of this array is: "<<p[count-1]<<endl;}
void maxofarray(atype*p,int count){for (int j=0;j<count-1;j++){for (int k=0;k<count-1-j;k++)if(p[k]>p[k+1]){atype temp;temp=p[k];p[k]=p[k+1];p[k+1]=temp;}}cout<<"\nthe max element of this array is: "<<p[count-1]<<endl;} 解析:本题考查的是考生对模板函数和简单的排序方法的综合应用。为了对于任何数据类型都能进行比较,应该使用模板类进行函数的参数的定义,而函数内部则使用了冒泡排序法得到最大的元素,实际上只需要一次两两比较就可以得到正确的答案了,考生可以自己试试看。