用同一个函数名对n(n<=10)个数据进行从小到大排序,数据类型可以是整数、浮点数,用函数重载实现
时间: 2023-05-30 20:03:19 浏览: 44
以下是用C++实现的函数重载代码:
```cpp
#include <iostream>
using namespace std;
// 声明函数模板
template <typename T>
void sort(T arr[], int n);
// 重载函数模板
template <typename T>
void sort(T arr[], int n) {
// 冒泡排序
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j+1]) {
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr1[] = {3, 1, 4, 2, 5};
float arr2[] = {3.3, 1.1, 4.4, 2.2, 5.5};
// 调用函数模板
sort(arr1, 5);
sort(arr2, 5);
// 输出排序结果
for (int i = 0; i < 5; i++) {
cout << arr1[i] << " ";
}
cout << endl;
for (int i = 0; i < 5; i++) {
cout << arr2[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
1 2 3 4 5
1.1 2.2 3.3 4.4 5.5
```
可以看到,我们通过函数模板实现了对整型数组和浮点型数组的排序,并且用同一个函数名`sort`来进行函数重载。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)