函数模板案例

案例描述:
利用函数模板封装一个排序的函数,可以对不同数据类型数组进行排序
排序规则从大到小,排序算法为选择排序
分别利用char数组和int数组进行测试
#include
using namespace std;

template
void jiaohuan(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
void test01()
{
//char数组
int a[7] = { 1,6,4,9,1,6,5 };

for (int c = 0; c < 7 - 1; c++)
{
	for (int d = 0; d < 7 - c - 1; d++)
	{
		if (a[d] < a[d + 1])
		{
			jiaohuan(a[d], a[d + 1]);
		}


	}
}//
for (int d = 0; d < 7; d++)
{
	cout << a[d] << endl;
}

}

//test02
void test02()
{
//char数组
char a[7] = “hasaqd”;

for (int c = 0; c < 7 - 1; c++)
{
	for (int d = 0; d < 7 - c - 1; d++)
	{
		if (a[d] < a[d + 1])
		{
			jiaohuan(a[d], a[d + 1]);
		}


	}
}//
for (int d = 0; d < 7; d++)
{
	cout << a[d] << endl;
}

}

int main()
{
test01();
test02();
system(“pause”);
return 0;
}

猜你喜欢

转载自blog.csdn.net/ADADQDQQ/article/details/108414719