概念
- 重载函数调用操作符的类,其对象称为函数对象
- 函数对象使用重载的()时,行为类似函数调用,也叫仿函数
特点
- 可以像函数一样调用
- 可以有自己的状态,成员属性
- 可以像参数一样传递
class MyAdd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
class Myprint
{
public:
Myprint()
{
this->count = 0;
}
int count;
void operator()(string test)
{
cout << test << endl;
this->count++;
}
};
void doPrint(Myprint& mp, string test)
{
mp(test);
}
void test01()
{
MyAdd myadd;
cout << myadd(1, 2) << endl;
Myprint myprint;
for( int i = 0; i < 10 ; i++)
{
myprint("hello world!");
}
cout << "the time of calling myprint is: " << myprint.count << endl;
doPrint(myprint, "Hello, c++!");
}
谓词
一元谓词
- 返回bool类型的仿函数称为谓词
- 如果
operator()
接受一个参数,称为一元谓词; - 如果
operator()
接受两个参数,称为二元谓词;
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
void test01()
{
vector<int> v;
for (int i = 0; i < 6; i++)
{
v.push_back(i);
}
vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
if (it == v.end())
{
cout << "not found" << endl;
}
else
{
cout << " Find a number bigger than 5: " << *it << endl;
}
}
二元谓词
class MyCompare
{
public:
int count;
class MyCompare()
{
this->count = 0;
}
bool operator()(int a, int b)
{
this->count++;
return a > b;
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(40);
v.push_back(20);
v.push_back(30);
v.push_back(50);
sort(v.begin(), v.end());
printVec<int>(v);
MyCompare mycompare;
sort(v.begin(), v.end(), mycompare);
printVec<int>(v);
}
内建算术仿函数
- 实现四则运算
negate
是一元运算,其余是二元运算
#include<functional>
void test01()
{
negate<int> n;
cout << n(50) << endl;
plus<int>p;
cout << p(2, 3) << endl;
minus<int> m;
cout << m(5, 2) << endl;
}
关系仿函数
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WAyryHeE-1605073301062)(https://i.loli.net/2020/11/10/DmFfnUoM7u4eAGP.png)]
void test01()
{
vector<int> v;
v.push_back(1);
v.push_back(3);
v.push_back(4);
v.push_back(3);
v.push_back(5);
printVec<int>(v);
sort(v.begin(), v.end(), greater<int>());
printVec<int>(v);
}
逻辑仿函数
void test01()
{
vector<bool> v;
v.push_back(1);
v.push_back(0);
v.push_back(1);
v.push_back(1);
v.push_back(0);
printVec<bool>(v);
vector<bool> v2;
v2.resize(v.size());
transform(v.begin(), v.end(), v2.begin(), logical_not<bool>());
printVec<bool>(v2);
}