#include <iostream>
#include<string>
using namespace std;
template<typename T, int n>
void Sort(T (&a)[n])//此处n的大小由编译器推断
{
int len = sizeof(a) / sizeof(*a);//获取数组中元素的个数
{
for(int i = 0; i < len - 1; i++)//冒泡排序
{
for(int j = 0; j < len - i - 1; j++)
{
if(a[j] > a[j+1])
{
T temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
}
//当调用函数的数组元素类型为字符串类型时,更改为字符串长度排序
template<int n>
void Sort(string (&a)[n])
{
int len = sizeof(a) / sizeof(*a);
for(int i = 0; i < len - 1; i++)//冒泡排序
{
for(int j = 0; j < len - i - 1; j++)
{
if(a[j].length() > a[j+1].length())
{
string temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
template<typename T, int n>
void Print(T (&a)[n])
{
int len = sizeof(a) / sizeof(*a);
for(int i = 0; i < len; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
int main()
{
char ch[5] = {'b', 'd', 'a', 'c', 'e'};
int nums[8] = {4, 5, 3, 7, 8, 0, 2, 8};
string str[4] = {"sdd", "sd", "dsfsf", "f"};
Sort(ch);
Sort(nums);
Sort(str);
Print(ch);
Print(nums);
Print(str);
return 0;
}
这里主函数我用了两种类型来验证,但是此函数不适用于字符串类型数组的长度排序。