【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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通