Processing math: 100%
\newcommand{\ord}[1]{\mathcal{O}\left(#1\right)} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\floor}[1]{\lfloor #1 \rfloor} \newcommand{\ceil}[1]{\lceil #1 \rceil} \newcommand{\opord}{\operatorname{\mathcal{O}}} \newcommand{\argmax}{\operatorname{arg\,max}} \newcommand{\str}[1]{\texttt{"#1"}}

2015年1月7日 星期三

在函式中傳入使用者自定函式的方法(C++ Functor 仿函式)

一般來說在函式中傳入使用者自定函式通常會用函數指標
但是C++ template提供了一個較為便利的函數參數,以物件的方式傳入
可支援一般函數或利用重載()運算子所定義的物件
詳情請看代碼:
#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;
}
view raw Functor.cpp hosted with ❤ by GitHub

沒有留言:

張貼留言