您好,登錄后才能下訂單哦!
仿函數(shù)與函數(shù)適配器如何正確的在c++中使用?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
所謂的仿函數(shù)(functor),是通過重載()運算符模擬函數(shù)形為的類?! ?/p>
因此,這里需要明確兩點:
1 仿函數(shù)不是函數(shù),它是個類;
2 仿函數(shù)重載了()運算符,使得它的對你可以像函數(shù)那樣子調(diào)用(代碼的形式好像是在調(diào)用函數(shù))。
for_each
這里的for循環(huán)語句有點冗余,想到了std::for_each ,為了使用for_each,我們需要定義一個函數(shù),如下:
void print( State* pstate ) { pstate->print(); }
于是就可以簡化為下面代碼:
std::for_each( vect.begin(), vect.end(), &print );
STL大致分為六大模塊:容器(container),算法(algorithm),迭代器(iterator),仿函數(shù)(functor),配接器(adapter),配置器(allocator)。其中仿函數(shù)是體積最小,觀念最簡單,但是在stl算法的搭配中起到了非常重要的作用,這是與簡單的lambda或者指針函數(shù)所不同的。
在stl中提供了大量有用的仿函數(shù),比如plus,minus,multiplies,divides,modulus,equal_to,not_equal_to,greater…很多很多,根據(jù)傳入的參數(shù)的個數(shù)我們可以分為只需要接受一個參數(shù)的仿函數(shù)(unary_function)和需要接收兩個參數(shù)的仿函數(shù)(binary_function)。
仿函數(shù)實現(xiàn)示例
//仿函數(shù)1,比較大小template<typename T> struct comp { bool operator()(T in1, T in2) const { return (in1>in2); } };comp<int> m_comp_objext; cout << m_comp_objext(6, 3) << endl; //使用對象調(diào)用 cout << comp<int>()(1, 2) << endl; //使用仿函數(shù)實現(xiàn)
在上面的代碼中,第一種調(diào)用方式是使用comp的定義的一個對象,然后通過這個對象來調(diào)用操作符(),來實現(xiàn)兩個數(shù)組的比較的;對于第二個調(diào)用comp()(1, 2)是產(chǎn)生一個臨時(無名的)對象。
2.2 仿函數(shù)詳細(xì)說明
在下面的使用場景(統(tǒng)計一個容器中的符合規(guī)定的元素),將說明之前提到的函數(shù)指針為什么不能在STL中替換掉仿函數(shù)
bool my_count(int num) { return (num < 5); }int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> v_a(a, a+10); cout << "count: " << std::count_if(v_a.begin(), v_a.end(), my_count);
在上面我們傳遞進(jìn)去了一個函數(shù)指針作為count_if的比較條件。但是現(xiàn)在根據(jù)新的需求,不再統(tǒng)計容器中小于5的變量個數(shù),改為了8或者3。那么最直接的方法就是加一個參數(shù)threshold就可以了,就像下面這樣
bool my_count(int num, int threshold) { return (num < threshold)); }
但是這樣的寫法STL中是不能使用的,而且當(dāng)容器中的元素類型發(fā)生變化的時候就不能使用了,更要命的是不能使用模板函數(shù)。
那么,既然多傳遞傳遞參數(shù)不能使用,那就把需要傳遞進(jìn)來的那個參數(shù)設(shè)置為全局的變量,那樣確實能夠?qū)崿F(xiàn)當(dāng)前情況下對閾值條件的修改,但是修改起來存在隱患(要是沒有初始化就調(diào)用怎么辦)。因而解決這樣問題的方式就是
方式就很好的兼容了STL。
template<typename T> struct my_count1 { my_count1(T a) { threshold = a; } T threshold; bool operator()(T num) { return (num < threshold); } };int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; std::vector<int> v_a(a, a+10);cout << "count: " << std::count_if(v_a.begin(), v_a.end(), my_count1<int>(8));
1.仿函數(shù)當(dāng)做排序準(zhǔn)則
#include <iostream> #include <string> #include <set> #include <algorithm> using namespace std;class Person { public: Person(string a, string b) : strFirstname(a), strLastname(b) {} public: string firstname() const { return strFirstname; } string lastname() const { return strLastname; } private: const string strFirstname; const string strLastname; };//仿函數(shù)實現(xiàn)自定義排序 class PersonSortCriterion { public: //仿函數(shù) //排序規(guī)則為:按照lastname升序排列,lastname相同時按firstname升序排列 bool operator()(const Person &p1, const Person &p2) { return (p1.lastname() > p2.lastname() || ((p2.lastname() <= p1.lastname()) && p1.firstname() > p2.firstname())); } }; int main(int argc, char *argv[]) { //類型重定義,并指定排序規(guī)則 typedef set<Person, PersonSortCriterion> PersonSet; PersonSet col1; //創(chuàng)建元素,并添加到容器 Person p1("Jay", "Chou"); Person p2("Robin", "Chou"); Person p3("Robin", "Lee"); Person p4("Bob", "Smith"); //向容器中插入元素 col1.insert(p1); col1.insert(p2); col1.insert(p3); col1.insert(p4); PersonSet::iterator pos; //輸出PersonSet中的所有元素 for (pos = col1.begin(); pos != col1.end(); ++pos) { cout << pos->firstname() << " " << pos->lastname() << endl; } cout << endl; system("pause"); return 0; }
有多種狀態(tài)的仿函數(shù)
#include <iostream> #include <list> #include<algorithm> using namespace std;class IntSequence { private: int value; //記錄內(nèi)部狀態(tài)的成員變量 public: IntSequence(int initialValue) : value(initialValue) { } //仿函數(shù) int operator()() { return value++; } };int main() { list<int> col1; //產(chǎn)生長度為9的序列,依次插值到col1容器的尾部 generate_n(back_inserter(col1), 9, IntSequence(1)); //1 2 3 4 5 6 7 8 9 for (auto t : col1) { cout << t << " "; } cout << endl; //替換col1容器中第2個到倒數(shù)第2個,從42開始 generate(++col1.begin(), --col1.end(), IntSequence(42)); //1 42 43 44 45 46 47 48 9 for (auto t : col1) { cout << t << " "; } cout << endl; system("pause"); return 0; }
仿函數(shù)都是傳值,而不是傳址的。因此算法并不會改變隨參數(shù)而來的仿函數(shù)的狀態(tài)。
比如:
IntSequence seq(1); //從1開始的序列 //從1開始向容器col1中插入9個元素 generate_n(back_inserter(col1), 9, seq); //仍然從1開始向容器col1中插入9個元素 generate_n(back_inserter(col1), 9, seq);
generate函數(shù)
#include <iostream> #include <algorithm> #include <array> #include <vector> #include <functional> using namespace std; int main(){ array<int,8> t1; //產(chǎn)生序列個100內(nèi)的隨機(jī)數(shù) generate(t1.begin(),t1.end(),[](){return rand()%100;}); //產(chǎn)生5個1000內(nèi)的隨機(jī)數(shù) generate_n(t1.begin(),5,[](){return rand()%1000;}); for_each(t1.begin(),t1.end(),[](int i){cout<<i<<endl;}); return 0; }
當(dāng)然,也有方法來解決上述使仿函數(shù)內(nèi)部狀態(tài)改變的問題。
方法有兩種:
1、以引用的方式傳遞仿函數(shù);
2、運用for_each()算法的返回值。
因為for_each()算法它返回其仿函數(shù)。也就是說,我們可以通過返回值可以取得仿函數(shù)的狀態(tài)。
以引用的方式傳遞仿函數(shù)
#include <iostream> #include <list> #include <algorithm>using namespace std;class IntSequence { private: int value; public: IntSequence(int initValue) : value(initValue) {} int operator()() { return value++; } };int main() { list<int> col1; IntSequence seq(1); //采用引用類型 generate_n<back_insert_iterator<list<int> >, int, IntSequence&>(back_inserter(col1), 4, seq); //1 2 3 4; for (auto t : col1) { cout << t << " "; } cout << endl; //相當(dāng)于重新構(gòu)建一個對象從42開始插入4個元素 generate_n(back_inserter(col1), 4, IntSequence(42)); //1 2 3 4; 42 43 44 45 for (auto t : col1) { cout << t << " "; } cout << endl; //前面使用的是引用類型,所以seq的內(nèi)部狀態(tài)已經(jīng)被改變了 //插值從上次完成后的5開始 //注意:這次調(diào)用仍然使用的是傳值類型 generate_n(back_inserter(col1), 4, seq); //1 2 3 4; 42 43 44 45; 5 6 7 8 for (auto t : col1) { cout << t << " "; } cout << endl; //上一次調(diào)用使用的是傳值類型,所以這次還是從5開始插值 generate_n(back_inserter(col1), 4, seq); //1 2 3 4; 42 43 44 45; 5 6 7 8; 5 6 7 8 for (auto t : col1) { cout << t << " "; } cout << endl; system("pause"); return 0; }
運用for_each()算法的返回值
#include <iostream> #include <vector> #include <algorithm> using namespace std;class MeanValue { private: long num; long sum; public: MeanValue() : num(0), sum(0) {} void operator() (int elem) { num++; sum += elem; } double value() { return static_cast<double>(sum) / static_cast<double>(num); } }; class Meansum { private: //long num; long sum; public: Meansum() : sum(0) {} void operator() (int elem) { sum += elem; } double value() { return sum; } }; int main() { vector<int> col1; for (int i = 1; i <= 8; ++i) { col1.push_back(i); } for (auto t : col1) { cout << t << " "; } cout << endl; MeanValue mv = for_each(col1.begin(), col1.end(), MeanValue()); Meansum sum = for_each(col1.begin(), col1.end(), Meansum()); cout << "Mean Value: " << mv.value() << endl; cout << "Mean sum: " << sum.value() << endl; system("pause"); return 0; }
判斷式與仿函數(shù)
判斷式就是返回布爾型的函數(shù)或者仿函數(shù)。對于STL而言,并非所有返回布爾值的函數(shù)都是合法的判斷式。這可能會導(dǎo)致很多出人意料的行為,比如下例:
#include <iostream> #include <list> #include <algorithm> using namespace std;class Nth { private: int nth; int count; public: Nth(int n) : nth(n), count(0) { } bool operator() (int) { return ++count == nth; } }; int main() { list<int> col1; for (int i = 1; i <= 9; ++i) { col1.push_back(i); } //1 2 3 4 5 6 7 8 9 for (auto t : col1) { cout << t << " "; } cout << endl; list<int>::iterator pos; pos = remove_if(col1.begin(), col1.end(), Nth(3)); col1.erase(pos, col1.end()); for (auto t : col1) { cout << t << " "; } cout << endl; system("pause"); }
函數(shù)配接器(函數(shù) 適配器)
函數(shù)配接器:能夠?qū)⒎潞瘮?shù)和另一個仿函數(shù)(或某個值,或某個一般函數(shù))結(jié)合起來的仿函數(shù)。
函數(shù)配接器包含在頭文件<functional>中。預(yù)定義的函數(shù)配接器如下表所示:
先弄清幾個概念,什么叫一元函數(shù),二元函數(shù)
1、一元函數(shù)一個參數(shù)
2、二元函數(shù) 兩個參數(shù)
3、一元謂詞 一個參數(shù),返回類型為bool型
4、二元謂詞 兩個參數(shù),返回類型為bool型
函數(shù)適配器是用來讓一個函數(shù)對象表現(xiàn)出另外一種類型的函數(shù)對象的特征。因為,許多情況下,我們所持有的函數(shù)對象或普通函數(shù)的參數(shù)個數(shù)或是返回值類型并不是我們想要的,這時候就需要函數(shù)適配器來為我們的函數(shù)進(jìn)行適配
C++中有三類適配器,分別是容器適配器,迭代器適配器和函數(shù)適配器,這里主要介紹函數(shù)適配器。
函數(shù)適配器用于特化和擴(kuò)展一元二元函數(shù)對象,函數(shù)適配器主要有以下兩類:
1 綁定器
該類適配器用于將二元函數(shù)適配成一元函數(shù)
將二元函數(shù)的一個參數(shù)綁定到一個特定的值上,將二元函數(shù)對象轉(zhuǎn)換成一元函數(shù)對象。
綁定器適配器有兩種:bind1st bind2nd。每個綁定器接受一個函數(shù)對象和一個值
bind1st將給定值綁定到二元函數(shù)對象的第一個實參
bind2nd將給定值綁定到二元函數(shù)對象的第二個實參
#include <iostream> #include <algorithm> #include <functional> #include <vector>using namespace std;bool is_odd(int n) { return n % 2 == 1; }int main(void) { int a[] = { 1, 2, 3, 4, 5 }; vector<int> v(a, a + 5); cout << count_if(v.begin(), v.end(), is_odd) << endl; //計算奇數(shù)元素的個數(shù) // 這里的bind2nd將二元函數(shù)對象modulus轉(zhuǎn)換為一元函數(shù)對象。 //bind2nd(op, value) (param)相當(dāng)于op(param, value) cout << count_if(v.begin(), v.end(),bind2nd(modulus<int>(), 2)) << endl; //bind1st(op, value)(param)相當(dāng)于op(value, param); //把4綁定為第一個參數(shù),即 4 < value //比4大的數(shù)字有幾個 cout << count_if(v.begin(), v.end(),bind1st(less<int>(), 4)) << endl; //把3綁定為第二個參數(shù),即 value < 3 //比3小的數(shù)字有幾個 cout << count_if(v.begin(), v.end(), bind2nd (less<int>(), 3)) << endl; //把3綁定為第二個參數(shù),即 value < 3 //not1 對第一個對象取反。 //對一元函數(shù)對象的結(jié)果取反 //比3小的數(shù)字有幾個的結(jié)果取反 cout << count_if(v.begin(), v.end(),not1( bind2nd (less<int>(), 3)) )<< endl; system("pause"); return 0; //輸出 3 3 1 2 3 }
關(guān)于仿函數(shù)與函數(shù)適配器如何正確的在c++中使用問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。