谓词
概念:
返回bool类型的仿函数吃呢改为谓词
如果operator()接受一个参数,那么叫做一元谓词
如果operator()接受两个参数,那么叫做二元谓词
#include<vector>
#include<algorithm>
class greaterfive
{
public:
bool operator()(int val)
{
return val>5;
}
};
void test1()
{
vector<int>v;
for(int i = 0;i<10;i++)
{
v.push_back(i);
}
vector<int>::iterator it = find_if(v.begin(),v.end(),greaterfive());
//参数列表中的pred表示bool类型的返回值
//传入一个匿名的函数对象
//如果找到会返回这个元素迭代器的位置
//未找到会返回end迭代器
cout<<*it<<endl;
}
二元谓词
#include<vector>
class mycompare
{
public:
bool operator()(int val1,int val2)
{
return val1>val2;
}
};
vector<int>v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
sort(v.begin(),v.end(),mycompare());
//重点,仿函数是一个类,一定要创建匿名的函数对象才可以使用
内建函数对象
概念:STL内建了一些函数对象
分类:
算数仿函数
关系仿函数
逻辑仿函数
用法:
这些仿函数所产生的对象,用法和一般函数完全相同
使用内建函数对象,需要引入头文件
#include
算术仿函数
功能描述:
实现四则运算
其中negate是一元运算,其他都是二元运算
仿函数原型:
template《class T》T plus《T 》 加法仿函数
template《class T》T minus《T 》 减法仿函数
template《class T》T multiply《T 》 乘法仿函数
template《class T》T divides《T 》 除法仿函数
template《class T》T modulus《T 》 取模仿函数
template《class T》T negate《T 》 取反仿函数
#include<functional>
void test1()
{
negate<int>n;
cout<<n(50)<<endl;
//对50取反,直接调用函数
plus<int>p;
cout<<p(10,20)<<endl;
//二元加法
}
关系仿函数
仿函数原型:
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》 小于等于
vector<int>v;
v.push.back(1);
v.push.back(3);
v.push.back(2);
v.push.back(4);
v.push.back(5);
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》 逻辑非
vector<int>v;
v.push_back(true);
v.push_back(false);
vector<int>v2;
v2.resize(v.size());
//目标容器要提前开辟空间
transform(v.begin(),v.end(),v2.begin(),logical_not<bool>());
//实现在搬运的同时进行逻辑运算