编写一个函数模板,求数组的最大元素,并写出调用此函数模板的完整程序,使得函数调用时,数组的类型可以是整型、双精度型、字符型。
时间: 2023-04-23 18:07:24 浏览: 129
函数模板如下:
```
template<typename T>
T max_element(T arr[], int size){
T max = arr[];
for(int i=1; i<size; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
}
```
完整程序如下:
```
#include<iostream>
using namespace std;
template<typename T>
T max_element(T arr[], int size){
T max = arr[];
for(int i=1; i<size; i++){
if(arr[i] > max){
max = arr[i];
}
}
return max;
}
int main(){
int arr1[] = {1, 2, 3, 4, 5};
double arr2[] = {1.1, 2.2, 3.3, 4.4, 5.5};
char arr3[] = {'a', 'b', 'c', 'd', 'e'};
cout<<"int数组最大元素为:"<<max_element(arr1, 5)<<endl;
cout<<"double数组最大元素为:"<<max_element(arr2, 5)<<endl;
cout<<"char数组最大元素为:"<<max_element(arr3, 5)<<endl;
return ;
}
```
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)