WordPress允许用户删除评论,宁波seo快速优化,模板小程序,苏州高端网站制作机构文章目录一、概念总结一、概念
仿函数又称函数对象#xff0c;即重载了函数调用运算符#xff08;#xff09;的类的对象。 优势#xff1a; 1.仿函数对象的内部可以有自己的状态#xff0c;可以实现一些其他的功能。 2.函数对象可以作为参数进行传递。
当仿函数类内重载…
文章目录一、概念总结一、概念
仿函数又称函数对象即重载了函数调用运算符的类的对象。 优势 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
0STL里内置了一些仿函数类型包括算术仿函数、关系仿函数、逻辑仿函数。
算数仿函数包括-*/, 取模取反。
#includeiostream
#includestring
#includefunctional//STL内部函数对象头文件
using namespace std;int main()
{//算术仿函数//加法plusinta;cout a(1, 2) endl;//减法minusinta1;cout a1(1, 2) endl;//乘法multipliesinta2;cout a2(1, 2) endl;//除法dividesinta3;cout a3(2, 1) endl;//取反仿函数negateintb;cout b(1) endl;//取模仿函数modulusintc;cout c(3,2) endl;system(pause);
}3
-1
2
2
-1
1关系仿函数包括,,,,。
#includeiostream
#includestring
#includelist
#includefunctional//STL内部函数对象头文件
using namespace std;int main()
{listintL;//插入L.push_back(1);L.push_back(2);listintL1;L1 L;//内置的关系仿函数,大于//L.sort(greaterint());//小于//L.sort(lessint());//小于等于L.sort(greater_equalint());for (listint::iterator i L.begin(); i ! L.end(); i){cout *i endl;}system(pause);
}逻辑运算符包括与或非。 listboolL1;L1.push_back(true);L1.push_back(false);for (listbool::iterator i L1.begin(); i ! L1.end(); i){cout *i endl;}listboolL2;L2.resize(L1.size());transform(L1.begin(), L1.end(), L2.begin(),logical_notbool());for (listbool::iterator i L2.begin(); i ! L2.end(); i){cout *i endl;}总结
对于简单的容器之间的运算可以使用内置的仿函数如果想自定义更复杂的仿函数就需要自己构建仿函数类。