【C++】用同一个函数名对n个数据进行从小到大排序,数据类型可以是整型,单精度型,双精度型,分别用函数重载、函数模板实现

it2024-11-14  4

用函数重载实现:

#include <iostream> using namespace std; int sort(int* p, int n) { for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (p[i] > p[j]) { int x; x = p[j]; p[j] = p[i]; p[i] = x; } } } for (int k = 0; k < n; k++) cout << p[k] << " "; return 0; } float sort(float* p, int n) { for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (p[i] > p[j]) { float x; x = p[j]; p[j] = p[i]; p[i] = x; } } } for (int k = 0; k < n; k++) cout << p[k] << " "; return 0; } double sort(double* p, int n) { for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (p[i] > p[j]) { double x; x = p[j]; p[j] = p[i]; p[i] = x; } } } for (int k = 0; k < n; k++) cout << p[k] << " "; return 0; } int main() { int a, n; cout << "您需要比较什么类型的数:\n1.整型\n2.单精度\n3.双精度" << endl << "输入类型前的编号:" << endl; cin >> a; cout << "请输入您需要比较数据的个数:" << endl; cin >> n; cout << "请输入" << n << "个需要比较的数\n"; if (a == 1) { int* p = new int[n]; for (int i = 0; i < n; i++) cin >> p[i]; sort(p, n); } if (a == 2) { double* p = new double[n]; for (int i = 0; i < n; i++) cin >> p[i]; sort(p, n); } if (a == 3) { float* p = new float[n]; for (int i = 0; i < n; i++) cin >> p[i]; sort(p, n); } return 0; }

用函数模板实现:

#include <iostream> using namespace std; template<typename T> T sort(T* p, int n) { for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (p[i] > p[j]) { T x; x = p[j]; p[j] = p[i]; p[i] = x; } } } for (int k = 0; k < n; k++) cout << p[k] << " "; return 0; } int main() { int a, n; cout << "您需要比较什么类型的数:\n1.整型\n2.单精度\n3.双精度" << endl << "输入类型前的编号:" << endl; cin >> a; cout << "请输入您需要比较数据的个数:" << endl; cin >> n; cout << "请输入" << n << "个需要比较的数\n"; if (a == 1) { int* p = new int[n]; for (int i = 0; i < n; i++) cin >> p[i]; sort(p, n); } if (a == 2) { double* p = new double[n]; for (int i = 0; i < n; i++) cin >> p[i]; sort(p, n); } if (a == 3) { float* p = new float[n]; for (int i = 0; i < n; i++) cin >> p[i]; sort(p, n); } return 0; }
最新回复(0)