用同一个函数名对n(n<=10)个数据进行从小到大排序,数据类型可以是整数、浮点数,用函数重载实现
时间: 2024-05-16 15:14:36 浏览: 11
可以使用函数重载来实现对整数数组和浮点数数组的排序。以下是示例代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
void sort(int arr[], int n) {
std::sort(arr, arr + n);
}
void sort(float arr[], int n) {
std::sort(arr, arr + n);
}
int main() {
int arr1[] = {5, 2, 7, 1, 9};
float arr2[] = {3.2, 1.5, 6.8, 2.1, 7.4};
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;
}
```
在上面的代码中,我们定义了两个 `sort` 函数,一个接受整数数组,另一个接受浮点数数组。在每个函数中,我们使用 `std::sort` 来对数组进行排序。在 `main` 函数中,我们分别调用这两个函数来对两个数组进行排序,并使用 `cout` 打印排序后的结果。
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)