用模板函数写冒泡排序

利用模板函数来写冒泡排序可以做到数据类型的多样性。

例子如下:

#include <iostream>
#define N 5
using namespace std;

template <typename T>
void get_num(T *a)
{
	
	for(int i=0;i<N;i++)
	{
		cin>>a[i];
	}
}

template <typename T>
void sort(T *a)
{
	T tmp;
	for(int i=0;i<N-1;i++)
	{
		for(int j=0;j<N-1-i;j++)
		{
			if(a[j]>a[j+1])
			{
				tmp=a[j];
				a[j]=a[j+1];
				a[j+1]=tmp;
			}
		}
	}
}

template <typename T>
void print(T *a)
{
	cout<<"*****"<<endl;
	for(int i=0;i<N;i++)
	{
		cout<<a[i]<<" ";
	}
	cout<<endl;
}

int main()
{
	int a[100]={0};
	get_num<int>(a);
	sort<int>(a);
	print<int>(a);
	
	return 0;
}

上面程序中,主函数用了int型,执行结果如下:

将主函数中数组类型改为double型,如下:

int main()
{
	double a[100]={0};
	get_num<double>(a);
	sort<double>(a);
	print<double>(a);
	
	return 0;
}

执行结果如下:

总结下来,使用模板函数使得仅有参数,返回值类型不同的函数只写一次。

猜你喜欢

转载自blog.csdn.net/ShiHongYu_/article/details/81347893
今日推荐