预定义函数对象
算法函数对象
加法:plus<Types>
减法:minus<Types>
乘法:multiplies<Types>
除法divides<Tpye>
求余:modulus<Tpye>
取反:negate<Type>
关系函数对象
等于equal_to<Tpye>
不等于not_equal_to<Type>
大于 greater<Type>
大于等于greater_equal<Type>
小于 less<Type>
小于等于less_equal<Type>
逻辑函数对象
逻辑与 logical_and<Type>
逻辑或logical_or<Type>
逻辑非logical_not<Type>
常用函数函数适配器
绑定器(binder): binder通过把二元函数对象的一个实参绑定到一个特殊的值上,将其转换成一元函数对象。C++标准库提供两种预定义的binder适配器:bind1st和bind2nd,前者把值绑定到二元函数对象的第一个实参上,后者绑定在第二个实参上。
取反器(negator) : negator是一个将函数对象的值翻转的函数适配器。标准库提供两个预定义的ngeator适配器:not1翻转一元预定义函数对象的真值,而not2翻转二元谓词函数的真值。
template<typename T>
class IsGreater
{
public:
IsGreater(T num)
{
this->m_num = num;
}
bool operator()(T &num)
{
return num > m_num;
}
private:
T m_num;
};
void Fun1()
{
string str1 = "aaa";
string str2 = "bbb";
plus<string> strAdd;
string str = strAdd(str1, str2);
cout << "字符串相加之后:" << str << endl;
//函数对象求大于2的个数
vector<int> v1;
for (int i = 0; i < 10; i++)
{
v1.push_back(i + 1);
}
int num = 2;
for (vector<int>::iterator it = v1.begin(); it < v1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
int num1 = count(v1.begin(), v1.end(), num);
cout << "大于2的个数(得到第一个直接返回):" << num1 << endl;
//谓词
int num2 = count_if(v1.begin(), v1.end(), IsGreater<int>(num));
cout << "大于2的个数:" << num2 << endl;
//预定义函数对象 结合适配器
int num3 = count_if(v1.begin(), v1.end(), bind2nd(greater<int>(), num));
cout << "大于2的个数:" << num3 << endl;
//求奇数的个数
int num4 = count_if(v1.begin(), v1.end(), bind2nd(modulus<int>(), num));
cout << "奇数的个数:" << num4 << endl;
int num5 = count_if(v1.begin(), v1.end(), not1(bind2nd(modulus<int>(), num)));
cout << "偶数的个数:" << num5 << endl;
}