但是C++ template提供了一個較為便利的函數參數,以物件的方式傳入
可支援一般函數或利用重載()運算子所定義的物件
詳情請看代碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
template<typename T,typename _Compare> | |
T min_element(T first,T last,_Compare cmp){ | |
//這種做法可以將函式當成物件傳入 | |
T ans=first; | |
while(++first!=last){ | |
if(cmp(*first,*ans))ans=first; | |
} | |
return ans; | |
} | |
//盡量使用const避免出錯,一般STL的傳入函式也請這樣使用 | |
bool const cmp(const int &a,const int &b){ | |
return a<b; | |
} | |
struct _cmp{ | |
bool operator ()(const int &a,const int &b)const{ | |
return a>b; | |
} | |
}; | |
template<typename T> | |
struct __cmp{ | |
bool operator ()(const T &a,const T &b)const{ | |
return a<b; | |
} | |
}; | |
int s[20]={1,5,6,-91,2,8,4,5,-5,-9,-4,-1,5,8,6,3,7,-9}; | |
//max:8 min:-91 | |
int main(){ | |
_cmp my_cmp;//創立一個比較物件 | |
printf("%d\n",*min_element(s,s+18,my_cmp));//8 | |
printf("%d\n",*min_element(s,s+18,cmp));//-91 | |
printf("%d\n",*min_element(s,s+18,_cmp()));//8 | |
printf("%d\n",*min_element(s,s+18,__cmp<int >()));//-91 | |
return 0; | |
} |
沒有留言:
張貼留言