【C++模版题目】求数组中最大元素(函数模版)

 

Description

Write a function template  largest_element()  that returns the largest value in an array.  The array may contain elements of any one data type. The function has two parameters.  The first parameters is the name of the array and the second parameter is the integer number of elements in the array. The return type of the function is the same type as its first parameter.

编写一个函数模板largest_element()用来计算数组的最大值。数组元素可以是任意数据类型。该函数有两个参数,第一个数数组名,第二个是数组元素的个数,返回值类型为数组元素类型。

 

Input

输入有3 行,每行数据的第1个数n(n<=10), 表示数组元素的个数,后面跟n个数组元素

Output

输出有3行,每行输出对应数组的最大元素值

Sample Input

5 3 7 1 9 6
4 5.7 8.9 2.4 3.1
6 fHyAxk

Sample Output

9
8.9
y

题解

复制代码
 1 #include<iostream>
 2 using namespace std;
 3 
 4 template <class T>
 5 T largest_element(T a[],int size)
 6 {
 7     T max = a[0];
 8     for(int i=1;i<size;i++)
 9     {
10         if(a[i]>max)
11             max=a[i];
12     }
13     return max;
14 }
15 
16 int main()
17 {
18     int n1,n2,n3;
19     
20     cin>>n1;
21     int a1[n1];
22     for(int i=0;i<n1;i++) cin>>a1[i]; 
23     cout<<largest_element(a1,n1)<<endl;
24     
25     cin>>n2;
26     double a2[n2];
27     for(int i=0;i<n2;i++) cin>>a2[i];
28     cout<<largest_element(a2,n2)<<endl;
29     
30     cin>>n3;
31     char a3[n3];    
32     for(int i=0;i<n3;i++) cin>>a3[i];
33     cout<<largest_element(a3,n3)<<endl;
34     
35     return 0;
36 } 
复制代码

 

posted @   杏花疏影  阅读(928)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示