1.算术函数对象
预定义的函数对象支持加、减、乘、除、求余和取反。调用的操作符是与 type 相关联的实例
加法: plus<Types>
如:plus<string> stringAdd;
sres = stringAdd(sva1,sva2);
减法: minus<Types>
乘法: multiplies<Types>
除法 divides<Tpye>
求余: modulus<Tpye>
取反: negate<Type>
如:negate<int> intNegate;
ires = intNegate(ires);
2.关系函数对象
等于 equal_to<Tpye>
例:equal_to<string> stringEqual;
sres = stringEqual(sval1,sval2);
不等于 not_equal_to<Type>
大于 greater<Type>
大于等于 greater_equal<Type>
小于 less<Type>
小于等于 less_equal<Type>
2.逻辑函数对象
逻辑与 logical_and<Type>
例:logical_and<int> indAnd;
ires = intAnd(ival1,ival2);
dres=BinaryFunc( logical_and<double>(),dval1,dval2);
逻辑或 logical_or<Type>
逻辑非 logical_not<Type>
例:logical_not<int> IntNot;
Ires = IntNot(ival1);
Dres=UnaryFunc( logical_not<double>,dval1);
函数适配器:
详细介绍见:
https://www.cnblogs.com/ssyfj/p/10794574.html
常见适配器:
1 绑定器( binder ): binder 通过把二元函数对象的一个实参绑定到一个特殊的值上,将其转换成一元函数对象。 C++标准库提供两种预定义的 binder 适配器: bind1st 和 bind2nd ,前者把值绑定到二元函数对象的第一个实参上,后者绑定在第二个实参上。
2 取反器 (negator) : negator 是一个将函数对象的值翻转的函数适配器。标准库提供两个预定义的 ngeator 适配器: not1 翻转一元预定义函数对象的真值 ,而 not2 翻转二元谓词函数的真值。
常用函数适配器列表如下:
bind1st(op, value)
bind2nd(op, value)
not1(op)
not2(op)
mem_fun_ref(op)
mem_fun(op)
ptr_fun(op)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <set>
#include <functional>
using namespace std;
void Print(const string& str)
{
cout << str << endl;
}
void fun()
{
//plus
plus<int> intAdd;
int a = 10;
int b = 20;
int c;
c = intAdd(a,b);
cout << "C:" << c << endl;
//greater
vector<string> vec1;
vec1.push_back("bbb");
vec1.push_back("zzz");
vec1.push_back("aaa");
vec1.push_back("ccc");
vec1.push_back("ccc");
vec1.push_back("ccc");
vec1.push_back("ccc");
sort(vec1.begin(),vec1.end(),greater<string>());
for_each(vec1.begin(), vec1.end(), Print);
//求"ccc"出现的次数
string str = "ccc";
//equal_to<string>()有两个参数,left参数来自容器,right参数来自str
//bind2nd函数适配器,把预定义函数对象和第二个参数进行绑定
//bind2nd( equal_to<string>(),str):容器中等于str的元素
//count_if只接受三个参数,可我们需要传四个参数,于是用到bind2nd
int num = count_if(vec1.begin(), vec1.end(), bind2nd( equal_to<string>(),str));
cout << num << endl;
}
class isGreat
{
public:
isGreat(int i)
{
m_num = i;
}
bool operator()(int& num)
{
if (num > m_num)
{
return true;
}
return false;
}
private:
int m_num;
};
void fun2()
{
vector<int> vec;
for (int i=0;i<10;i++)
{
vec.push_back(i + 1);
}
for (vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//通过谓词求大于2的个数
int num1 = count_if(vec.begin(), vec.end(), isGreat(2));
cout << "num1:" << num1 << endl;
//通过预定义的函数对象求大于2的个数
//greater<int>()的左参数是容器的每一个元素,右参数为2
int num2 = count_if(vec.begin(), vec.end(), bind2nd(greater<int>(), 2));
cout << "num2:" << num2 << endl;
//求奇数的个数 modulus用来求余
int num3 = count_if(vec.begin(), vec.end(), bind2nd(modulus<int>(), 2));
cout << "num3:" << num3 << endl;
//求偶数的个数 not1用来取反
int num4 = count_if(vec.begin(), vec.end(), not1(bind2nd(modulus<int>(), 2)));
cout << "num4:" << num4 << endl;
}
void main()
{
fun();
fun2();
system("pause");
}