即STL内部建立的一些函数对象
分类:
- 算术仿函数
- 关系仿函数
- 逻辑仿函数
用法:
- 这些仿函数所使用产生的对象,用法和一般函数完全相同
- 使用内建函数对象,需要引入头文件#include<functional>
算术仿函数
功能描述:
- 实现四则运算
- 其中negate是一元运算
仿函数原型:
- 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> //取反仿函数
#include<iostream>
#include<vector>
#include<functional>
//#include<stdio.h>
using namespace std;
int main()
{
negate<int>n;
cout<<n(50)<<endl;
plus<int>p;
cout<<p(10,20)<<endl;
return 0;
}
关系仿函数
功能描述:
- 实现关系对比
仿函数原型:
- 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> //小于等于
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
int main()
{
vector<int>a;
a.push_back(2);
a.push_back(4);
a.push_back(1);
a.push_back(3);
sort(a.begin(),a.end(),greater<int>());
for(vector<int>::iterator it=a.begin();it!=a.end();it++)
cout<<*it<<" ";
return 0;
}
逻辑仿函数
功能描述:
- 实现逻辑运算
仿函数原型:
- template<class T> bool logical_and<T> //逻辑与
- template<class T> bool logical_or<T> //逻辑或
- template<class T> bool logical_not<T> //逻辑非
#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
using namespace std;
int main()
{
vector<bool>a;
a.push_back(true);
a.push_back(true);
a.push_back(true);
a.push_back(false);
//sort(a.begin(),a.end(),greater<int>());
for(vector<bool>::iterator it=a.begin();it!=a.end();it++)
cout<<*it<<" ";
cout<<endl;
vector<bool>b;
b.resize(a.size());//搬运之前一定要给目标容器开辟空间
transform(a.begin(),a.end(),b.begin(),logical_not<bool>());
for(vector<bool>::iterator it=b.begin();it!=b.end();it++)
cout<<*it<<" ";
return 0;
}