一个程序,用同一个函数名对3个数据进行从大到小排序, 数据类型可以是整型、单精度型、双精度型。用重载函数实现
时间: 2023-05-28 16:04:53 浏览: 54
下面是一个用重载函数实现对整型、单精度型、双精度型数据从大到小排序的程序:
```c++
#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 = i + 1; j < n; j++) {
if (arr[i] < arr[j]) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
// 重载函数
void sort(int* arr, int n)
{
sort<int>(arr, n);
}
void sort(float* arr, int n)
{
sort<float>(arr, n);
}
void sort(double* arr, int n)
{
sort<double>(arr, n);
}
int main()
{
int a[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3 };
float b[] = { 3.14f, 1.23f, 4.56f, 1.23f, 5.67f, 9.87f, 2.34f, 6.78f, 5.67f, 3.14f };
double c[] = { 3.14159, 1.23456, 4.56789, 1.23456, 5.67890, 9.87654, 2.34567, 6.78901, 5.67890, 3.14159 };
sort(a, 10);
sort(b, 10);
sort(c, 10);
for (int i = 0; i < 10; i++) {
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < 10; i++) {
cout << b[i] << " ";
}
cout << endl;
for (int i = 0; i < 10; i++) {
cout << c[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
9 6 5 5 4 3 3 2 1 1
9.87 6.78 5.67 5.67 4.56 3.14 3.14 2.34 1.23 1.23
9.87654 6.78901 5.6789 5.6789 4.56789 3.14159 3.14159 2.34567 1.23456 1.23456
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)