生活随笔
收集整理的這篇文章主要介紹了
C++ 仿函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一,概述
? ? ? ? 仿函數(functor),就是使一個類的使用看上去象一個函數。其實現就是類中實現一個operator(),這個類就有了類似函數的行為,就是一個仿函數類了。
有些功能的的代碼,會在不同的成員函數中用到,想復用這些代碼。
? ? ? ? ? ? ? ? ? ? ? ? ? ? 1)公共的函數,可以,這是一個解決方法,不過函數用到的一些變量,就可能成為公共的全局變量,再說為了復用這么一片代碼,就要單立出一個函數,也不是很好維護。
? ? ? ? ? ? ? ? ? ? ? ? ? ? 2)仿函數,寫一個簡單類,除了那些維護一個類的成員函數外,就只是實現一個operator(),在類實例化時,就將要用的,非參數的元素傳入類中。
二,仿函數(functor)在各編程語言中的應用
1)C語言使用函數指針和回調函數來實現仿函數,例如一個用來排序的函數可以這樣使用仿函數
[html]?view plaincopy
#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);//起始地址,個數,元素大小,回調函數??? ???int??x;?? ???for?(x?=?0;?x?<?5;?x++)?? ??????????printf("%i\n",?list[x]);?? ???????????????????? ???return?0;?? }?? ? ? ? ? 2)在C++里,我們通過在一個類中重載括號運算符的方法使用一個函數對象而不是一個普通函數。
[html]?view plaincopy
#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;??? }???
三,仿函數在STL中的定義
? ? ? ? 要使用STL內建的仿函數,必須包含<functional>頭文件。而頭文件中包含的仿函數分類包括
? ? ? ? ?1)算術類仿函數
? ? ? ? ? ? ? ?加:plus<T>
? ? ? ? ? ? ? ?減:minus<T>
? ? ? ? ? ? ? ?乘:multiplies<T>
? ? ? ? ? ? ? ?除:divides<T>
? ? ? ? ? ? ? ?模取:modulus<T>
? ? ? ? ? ? ? ?否定:negate<T>
例子:
[html]?view plaincopy
#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)關系運算類仿函數
? ? ? ? ? ? ? ?等于:equal_to<T>
? ? ? ? ? ? ? ?不等于:not_equal_to<T>
? ? ? ? ? ? ? ?大于:greater<T>
? ? ? ? ? ? ? ?大于等于:greater_equal<T>
? ? ? ? ? ? ? ?小于:less<T>
? ? ? ? ? ? ? ?小于等于:less_equal<T>
? ? ? ? ? ? ? 從大到小排序:
[html]?view plaincopy
#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)邏輯運算仿函數
? ? ? ? ? ? ? ? ?邏輯與:logical_and<T>
? ? ? ? ? ? ? ? ?邏輯或:logical_or<T>
? ? ? ? ? ? ? ? ?邏輯否:logical_no<T>
總結
以上是生活随笔為你收集整理的C++ 仿函数的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。