运用函数模板求数组4数中的最大值
时间: 2024-02-25 14:52:32 浏览: 34
可以使用函数模板来实现这个功能:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
template<typename T>
T array_max(T arr[], int size) {
return *max_element(arr, arr + size);
}
int main() {
int arr1[] = {1, 2, 3, 4};
double arr2[] = {1.1, 2.2, 3.3, 4.4};
cout << "max of arr1 is " << array_max(arr1, 4) << endl;
cout << "max of arr2 is " << array_max(arr2, 4) << endl;
return 0;
}
```
在上面的代码中,我们定义了一个函数模板 `array_max`,它接受一个数组和数组大小作为参数,返回数组中的最大值。在 `main` 函数中,我们分别定义了两个数组 `arr1` 和 `arr2`,并分别调用了 `array_max` 函数来求解它们的最大值。由于 `array_max` 是一个函数模板,因此我们不需要指定其参数类型,编译器会根据传入的参数自动推导出所需的类型。
相关问题
函数模板求数组数中的最大值
可以使用以下的函数模板来求取数组中的最大值:
```cpp
template<typename T, size_t N>
T max_array(T (&arr)[N]) {
T max_val = arr[0];
for(size_t i=1; i<N; ++i) {
if(arr[i] > max_val) {
max_val = arr[i];
}
}
return max_val;
}
```
其中,函数模板接受一个类型为T、大小为N的数组的引用,并返回数组中的最大值。函数模板中使用了模板的两个参数,T 表示数组中元素的类型,N 表示数组的大小。在函数内部,使用一个 for 循环来遍历数组中的元素,不断更新最大值,最终返回最大值。
使用示例:
```cpp
int arr[] = {1, 2, 3, 4, 5};
int max_val = max_array(arr);
std::cout << max_val << std::endl; // 输出 5
```
需要注意的是,函数模板的参数推导规则可以让我们在调用函数时省略模板参数,编译器会自动推导出模板参数的类型和大小。因此,我们可以直接传递一个数组给函数模板,而不用显式指定模板参数。
函数模板求数组中的最大数
可以使用函数模板和数组作为参数来实现求解数组中的最大数,具体代码如下:
```C++
#include <iostream>
using namespace std;
template <typename T>
T maxArray(T arr[], int len){
T maxNum = arr[0];
for(int i = 1; i < len; i++){
if(arr[i] > maxNum){
maxNum = arr[i];
}
}
return maxNum;
}
int main(){
int intArr[] = {3, 5, 2, 8, 1};
double doubleArr[] = {1.5, 2.7, 0.8, 3.9, 2.1};
cout << "The maximum number in int array is " << maxArray(intArr, 5) << endl;
cout << "The maximum number in double array is " << maxArray(doubleArr, 5) << endl;
return 0;
}
```
在上述代码中,我们定义了一个函数模板 `maxArray`,它接受两个参数,分别是数组 `arr` 和数组长度 `len`。在函数中,我们使用一个变量 `maxNum` 来存储数组中的最大数,然后遍历整个数组,如果当前元素比 `maxNum` 大,则将其赋值给 `maxNum`。最终,函数返回 `maxNum`。
在 `main` 函数中,我们定义了两个数组 `intArr` 和 `doubleArr`,分别包含整型和双精度浮点型数据。然后调用函数模板 `maxArray` 来求解这两个数组中的最大数,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)