文章目錄
- 一、概念
- 總結
一、概念
仿函數又稱函數對象,即重載了函數調用運算符()的類的對象。
優勢:
1.仿函數對象的內部可以有自己的狀態,可以實現一些其他的功能。
2.函數對象可以作為參數進行傳遞。
當仿函數類內重載的返回值是bool類型被稱為謂詞,形參為1個為1元謂詞,2個是2元謂詞。
class Compare
{
public:Compare(){n = 0;}//一元謂詞bool operator()(int a){n++;return a > 5; }//二元謂詞bool operator()(int a, int b){n++;return a > b; }int n;
};bool Print(Compare& c, int a, int b)
{return c(a, b);
}int main()
{Compare c;//函數對象//調用重載()cout << c(1, 2) << endl;cout << c(3, 2) << endl;cout << c(2, 1) << endl;//可實現計數功能cout << c.n << endl;//作為參數傳遞cout << Print(c, 3, 6) << endl;system("pause");
}
0
1
1
3
0
STL里內置了一些仿函數類型,包括算術仿函數、關系仿函數、邏輯仿函數。
算數仿函數包括+,-,*,/, 取模,取反。
#include<iostream>
#include<string>
#include<functional>//STL內部函數對象頭文件
using namespace std;int main()
{//算術仿函數//加法plus<int>a;cout << a(1, 2) << endl;//減法minus<int>a1;cout << a1(1, 2) << endl;//乘法multiplies<int>a2;cout << a2(1, 2) << endl;//除法divides<int>a3;cout << a3(2, 1) << endl;//取反仿函數negate<int>b;cout << b(1) << endl;//取模仿函數modulus<int>c;cout << c(3,2) << endl;system("pause");
}
3
-1
2
2
-1
1
關系仿函數包括>,<,=,<=,>=,!=。
#include<iostream>
#include<string>
#include<list>
#include<functional>//STL內部函數對象頭文件
using namespace std;int main()
{list<int>L;//插入L.push_back(1);L.push_back(2);list<int>L1;L1 = L;//內置的關系仿函數,大于//L.sort(greater<int>());//小于//L.sort(less<int>());//小于等于L.sort(greater_equal<int>());for (list<int>::iterator i = L.begin(); i != L.end(); i++){cout << *i << endl;}system("pause");
}
邏輯運算符包括與或非。
list<bool>L1;L1.push_back(true);L1.push_back(false);for (list<bool>::iterator i = L1.begin(); i != L1.end(); i++){cout << *i << endl;}list<bool>L2;L2.resize(L1.size());transform(L1.begin(), L1.end(), L2.begin(),logical_not<bool>());for (list<bool>::iterator i = L2.begin(); i != L2.end(); i++){cout << *i << endl;}
總結
對于簡單的容器之間的運算可以使用內置的仿函數,如果想自定義更復雜的仿函數,就需要自己構建仿函數類。