一,概述 仿函數(shù)(functor),就是使一個類的使用看上去象一個函數(shù)。其實現(xiàn)就是類中實現(xiàn)一個Operator(),這個類就有了類似函數(shù)的行為,就是一個仿函數(shù)類了。 有些功能的的代碼,會在不同的成員函數(shù)中用到,想復(fù)用這些代碼。
1)公共的函數(shù),可以,這是一個解決方法,不過函數(shù)用到的一些變量,就可能成為公共的全局變量,再說為了復(fù)用這么一片代碼,就要單立出一個函數(shù),也不是很好維護(hù)。
2)仿函數(shù),寫一個簡單類,除了那些維護(hù)一個類的成員函數(shù)外,就只是實現(xiàn)一個operator(),在類實例化時,就將要用的,非參數(shù)的元素傳入類中。
二,仿函數(shù)(functor)在各編程語言中的應(yīng)用 1)C語言使用函數(shù)指針和回調(diào)函數(shù)來實現(xiàn)仿函數(shù),例如一個用來排序的函數(shù)可以這樣使用仿函數(shù)
[html] view plain copy#include <stdio.h> #include <stdlib.h> //int sort_function( const void *a, const void *b); int sort_function( const void *a, const void *b) { return *(int*)a-*(int*)b; } int main() { int list[5] = { 54, 21, 11, 67, 22 }; qsort((void *)list, 5, sizeof(list[0]), sort_function);//起始地址,個數(shù),元素大小,回調(diào)函數(shù) int x; for (x = 0; x < 5; x++) PRintf("%i/n", list[x]); return 0; } 2)在C++里,我們通過在一個類中重載括號運(yùn)算符的方法使用一個函數(shù)對象而不是一個普通函數(shù)。[html] view plain copy#include <iostream> #include <algorithm> using namespace std; template<typename T> class display { public: void operator()(const T &x) { cout<<x<<" "; } }; int main() { int ia[]={1,2,3,4,5}; for_each(ia,ia+5,display<int>()); return 0; } 三,仿函數(shù)在STL中的定義要使用STL內(nèi)建的仿函數(shù),必須包含<functional>頭文件。而頭文件中包含的仿函數(shù)分類包括
1)算術(shù)類仿函數(shù)
加:plus<T>
減:minus<T>
乘:multiplies<T>
除:divides<T>
模取:modulus<T>
否定:negate<T>
例子:
[html] view plain copy#include <iostream> #include <numeric> #include <vector> #include <functional> using namespace std; int main() { int ia[]={1,2,3,4,5}; vector<int> iv(ia,ia+5); cout<<accumulate(iv.begin(),iv.end(),1,multiplies<int>())<<endl; cout<<multiplies<int>()(3,5)<<endl; modulus<int> modulusObj; cout<<modulusObj(3,5)<<endl; // 3 return 0; } 2)關(guān)系運(yùn)算類仿函數(shù)等于:equal_to<T>
不等于:not_equal_to<T>
大于:greater<T>
大于等于:greater_equal<T>
小于:less<T>
小于等于:less_equal<T>
從大到小排序:
[html] view plain copy#include <iostream> #include <algorithm> #include <vector> using namespace std; template <class T> class display { public: void operator()(const T &x) { cout<<x<<" "; } }; int main() { int ia[]={1,5,4,3,2}; vector<int> iv(ia,ia+5); sort(iv.begin(),iv.end(),greater<int>()); for_each(iv.begin(),iv.end(),display<int>()); return 0; } 3)邏輯運(yùn)算仿函數(shù)邏輯與:logical_and<T>
邏輯或:logical_or<T>
邏輯否:logical_no<T>
4:附錄
class AA
{
public:
AA(int a)
:_a(a)
{
}
booloperator > (constAA & other)const
{
return_a > other._a;
}
public:
int _a;
};
int main(int argc,const char * argv[]) {
std::vector<AA> ve{6,7,2,4,8,1,0};
std::sort(ve.begin(), ve.end(),std::greater<AA>());
for (auto it : ve)
{
printf("%d ", it._a);
}
}
新聞熱點
疑難解答