标签:
1 #include<iostream> 2 using namespace std; 3 4 5 //function template 6 template<class T> 7 void sort(T* array,int len,bool(*compare)(T& a,T& b)) 8 { 9 10 T temp; 11 for(int i=0;i<len;i++) //bubble sort 12 { 13 for(int j=len-1;j>i;j--) 14 { 15 if(compare(array[j],array[j-1])) 16 { 17 temp=array[j]; 18 array[j]=array[j-1]; 19 array[j-1]=temp; 20 } 21 } 22 } 23 } 24 25 template<class T> 26 bool ascend(T& a,T& b) 27 { 28 return a<b?true:false; 29 } 30 31 template<class T> 32 bool descend(T& a,T& b) 33 { 34 static int count=0; //caculate the number of the function 35 count++; 36 cout<<count<<"float"<<endl; 37 return a>b?true:false; 38 } 39 40 int main() 41 { 42 int arrayInt[10]={1,4,2,9,5,7,3,6,0,8}; 43 float arrayFloat[10]={1.1,4.0,2.0,9.0,5.0,7.0,3.0,6.0,0.0,8.0}; 44 sort<int>(arrayInt,10,ascend<int>); 45 for(int i=0;i<10;i++) 46 { 47 cout<<arrayInt[i]<<""; 48 } 49 cout<<endl; 50 sort<float>(arrayFloat,10,descend<float>); 51 for(int i=0;i<10;i++) 52 { 53 cout<<arrayFloat[i]<<" "; 54 } 55 cout<<endl; 56 57 return 0; 58 }
标签:
原文地址:http://www.cnblogs.com/wxquare/p/4678028.html