内建函数对象意义
概念:
分类:
用法:
- 这些仿函数所产生的对象,用法和一般函数完全相同
- 使用内建函数对象,需要引入头文件#inlcude<>functional
算数仿函数
功能描述:
- 实现四则远算
- 其中negate是一团运算,其他都是二元运算
函数原型:
- template T pulus //加法仿函数
- template T minus //减法仿函数
- template T multiplies //乘法仿函数
- template T divides //除法仿函数
- template T modulus //取模仿函数
- template T negate //取反仿函数
示例:
void test01()
{
negate<int> n;
cout << n(50) << endl;
}
void test02()
{
plus<int>p;
cout << p(10, 20) << endl;
minus<int>m;
cout << m(100, 20) << endl;
multiplies<int>mu;
cout << mu(10, 20) << endl;
divides<int>d;
cout << d(20, 20) << endl;
modulus<int>mo;
cout << mo(10, 20) << endl;
}
关系仿函数
函数原型:
- template bool equal_to //等于
- template bool not_equal_to //不等于
- template bool greater //大于
- template bool greater_equal //大于等于
- template bool less //小于
- template bool less_equal //小于等于
示例:
class MyCompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
void test01()
{
vector<int>v;
v.push_back(20);
v.push_back(50);
v.push_back(10);
v.push_back(30);
v.push_back(40);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
sort(v.begin(), v.end(), greater<int>());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
逻辑仿函数
函数原型:
- template bool logical_and //逻辑与
- template bool logical_or //逻辑或
- template bool logical_not //逻辑非
示例:
void test01()
{
vector<bool>v;
v.push_back(true);
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;
vector<bool>v1;
v1.resize(v.size());
transform(v.begin(), v.end(), v1.begin(), logical_not<bool>());
for (vector<bool>::iterator it = v1.begin(); it != v1.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}