函数对象
重载函数调用操作符的类,其对象称为函数对象,函数对象使用重载的()时,行为类似函数调用,也叫仿函数
函数对象()本质是一个类,不是一个函数
- 函数对象的使用
1. 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
2. 函数对象超出普通函数的概念,函数对象可以有自己的状态
3.函数对象可以作为参数传递
示例:
class MyAdd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
void test01()
{
MyAdd myAdd;
cout << myAdd(10, 10) << endl;
}
class MyPrint
{
public:
MyPrint()
{
this->count = 0;
}
int operator()(string test)
{
cout << test << endl;
this->count++;
}
int count;//内部自己状态
};
void test01()
{
MyPrint myPrint;
myPrint("hello world");
cout << "调用次数为:" << endl;
}
void doPrint(MyPrint& mp, string test)
{
mp(test);
}
void test3()
{
MyPrint mypPrint;
doPrint(mypPrint, "hello");
}
谓词
返回布尔类型的仿函数叫谓词
如果operator()接受一个参数叫做一元谓词,接收两个参数叫做二元谓词
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
void test01()
{
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//查找容器中有没有大于5的数字
vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());//传进来一个匿名的函数对象
if (it == v.end())
{
cout << "nope" << endl;
}
else
{
cout << *it << endl;
}
}
输出:
6
请按任意键继续. . .
二元谓词
class Compare
{
public:
bool operator()(int val1, int val2)
{
return val1 > val2;
}
};
内建函数对象
STL内建了一些函数对象,需要引入头文件
1. 算术仿函数
2. 关系仿函数
3. 逻辑仿函数
-
实现四则运算
template<class T> T plus<T> template<class T> T minus<T> template<class T> T multiplies<T> template<class T> T divides<T> template<class T> T modulus<T> template<class T> T negate<T>//一元运算,其余为二元 negate<int> n; cout << n(50) << endl; plus<int>p; cout << p(10, 20);
-
实现关系对比
template<class T> bool equal_to<T> template<class T> bool not_equal_to<T> template<class T> bool greater<T> template<class T> bool greater_equal<T> template<class T> bool less<T> template<class T> bool less_equal<T>
示例:
sort(v.begin(), v.end(), greater<int>());//匿名函数对象
-实现逻辑运算
template<class T> bool logical_and<T>
template<class T> bool logical_or<T>
template<class T> bool logical_not<T>
//利用逻辑非,将容器v搬运到容器v2中,并执行取反操作
vector<bool> v2;
v2.resize(v.size())
transform(v.begin(), v.end(), v2.begin(), logical_not<bool>()) //搬运算法,目标容器需要提前开辟