- 算术仿函数
- 关系仿函数
- 逻辑仿函数
- 这些仿函数所产生的对象,用法和一半函数完全相同
- 使用这些内建函数对象,需要引入头文件#include
1 实现四则运算
其中negate是一元运算,其他都是二元运算
仿函数原型:
template T plus //加法仿函数
template T minus //减法仿函数
template T multiplies //乘法仿函数
template T divides //除法仿函数
template T modulus //取模仿函数
template T negate //取反仿函数
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
#include<functional>
//negate 取反仿函数
void test01()
{
negate<int> n;
cout << n(50) << endl;
}
//plus 加法仿函数
void test02()
{
plus<int> n;
cout << n(50,50) << endl;
}
//modulus 取模仿函数
void test03()
{
modulus<int> n;
cout << n(123, 50) << endl;
}
int main()
{
test01();
test02();
test03();
return 0;
}
2 实现关系对比 用的最多的就是大于,因为默认情况下像排序都是小于
仿函数原型:
template bool equal_to //等于
template bool not_equal_to //不等于
template bool greater //大于
template bool greater_equal //大于等于
template bool less //小于
template bool less_equal //小于等于
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
#include<functional>
class Mycompare
{
public:
bool operator()(int val1, int val2)
{
return val1 > val2;
}
};
void test01()
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(10);
v.push_back(80);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//自己写个仿函数从小到大,意思就是写个二元谓词
sort(v.begin(), v.end(), Mycompare());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
}
int main()
{
test01();
return 0;
}
3 实现逻辑运算
函数原型:
template bool logical_and //逻辑与
template bool logical_or //逻辑或
template bool logical_not //逻辑非
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
#include<functional>
void test01()
{
vector<bool> v;
v.push_back(true);
v.push_back(false);
v.push_back(true);
v.push_back(false);
for (vector<bool>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//执行逻辑非运算,把容器v中的搬运到v2中,并执行逻辑非运算
vector<bool> v2;
v2.resize(v.size()); //搬运空间
transform(v.begin(), v.end(), v2.begin(), logical_not<bool>());
for (vector<bool>::iterator it = v2.begin(); it != v2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
test01();
return 0;
}