实现:函数模板实现不同数据类型数组进行排序

示例代码:

#include<iostream>

using namespace std;

template<class T>
void Swap(T &a,T &b) { // int * a = &arr[max]  int * b = &arr[i]  交换不同类型的数值
	T temp;
	temp = a;
	a = b;
	b = temp;
}

template<class T>
void to_sort(T arr[], int num) {  //接收不同的参数类型的数组
	for (int i = 0; i < num; i++) {
		int max = i;
		for (int j = i + 1; j < num; j++) {
			if (arr[max] > arr[j]) {
				max = j;
			}
		}
		if (max != i) {
			Swap(arr[max], arr[i]);
		}
	}
}

template<class T>
void to_print(T arr[], int num) {  //arr[] 这种传参写法相当于引用  接收并且输出不同类型的数组中的值
	for (int i = 0; i < num; i++) {
		cout << arr[i];
	}
}

int main() {
	char a[] = "loxpam";
	int num = sizeof(a) / sizeof(a[0]); //计算数量
	to_sort(a, num);
	to_print(a, num);
	
	cout << endl;

	int b[] = { 1,2,4,3,7,6,4 };
	int num_arr = sizeof(a) / sizeof(a[0]);//计算数量
	to_sort(b, num_arr);
	to_print(b, num_arr);
	system("pause");
	return 0;

}
原文地址:https://www.cnblogs.com/zpchcbd/p/11908184.html