文章目录
- 一、概念
- 总结
一、概念
仿函数又称函数对象,即重载了函数调用运算符()的类的对象。
优势:
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;}
总结
对于简单的容器之间的运算可以使用内置的仿函数,如果想自定义更复杂的仿函数,就需要自己构建仿函数类。