qfedu-cpp-level/day6/template/t2.cpp

56 lines
1.1 KiB
C++
Raw Permalink Normal View History

2023-08-14 17:20:39 +08:00
// 使用函数模版实现对 char 和 int 数组的排序和打印
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
template <typename T>
void sort(T arr[], int size)
{
for (int i = 0; i < size - 1; i++)
{
int min = i;
for (int j = i + 1; j < size; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
}
if (min != i)
{
arr[i] ^= arr[min];
arr[min] ^= arr[i];
arr[i] ^= arr[min];
// T temp = arr[i];
// arr[i] = arr[min];
// arr[min] = temp;
}
}
}
template <typename T>
void printArr(T arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr1[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 0};
char arr2[] = {'a', 'c', 'e', 'G', 'I', 'b', 'd', 'f', 'h', 'j'};
int size1 = sizeof(arr1) / sizeof(arr1[0]);
int size2 = sizeof(arr2) / sizeof(arr2[0]);
sort(arr1, size1);
sort(arr2, size2);
printArr(arr1, size1);
printArr(arr2, size2);
return 0;
}