|
关于模板函数的使用,百度了一个例子,就放在这里吧:- #include<iostream>
- using namespace std;
- template <typename T>
- T *fun(T a[],int n)
- {
- int i = 0;
- T temp;
- for(i=0;i<n-1;i++)
- for(int j=i+1;j<n;j++)
- {
- if(a[i]>a[j])
- {
- temp=a[i];
- a[i]=a[j];
- a[j]=temp;
- }
- }
- return a;
- }
- template<class T>
- void display(T a[],int n)
- {
- for(int i=0;i<n;i++)
- cout<<a[i]<<' ';
- cout<<endl;
- }
- int main()
- {
- int a[]={1,3,6,7,2,9};
- double b[]={1.3,2.8,6.9,7.1,5.6};
- cout << "排序前:";
- display(a,sizeof(a)/sizeof(a[0]));
- fun(a, sizeof(a)/sizeof(a[0]));
- cout << "排序后:";
- display(a,sizeof(a)/sizeof(a[0]));
- cout << endl;
- cout << "排序前:";
- display(b,sizeof(b)/sizeof(b[0]));
- fun(b, sizeof(b)/sizeof(b[0]));
- cout << "排序后:";
- display(b,sizeof(b)/sizeof(b[0]));
- system("pause");
- }
复制代码
|
|