文章目录
一、内建函数的对象意义
1、概念
STL 内建了一些函数对象
2、分类
①算数仿函数
②关系仿函数
③逻辑仿函数
3、用法
①这些仿函数所产生的对象,用法和一般函数完全相同
②使用内建函数对象,需要引入头文件#include
二、算数仿函数
1、功能描述
①实现四则运算
②其中negate时一元运算,其他都是二元运算
2、仿函数原型
①template T plus //加法仿函数
②template T minus //减法仿函数
③template T multiplies //乘法仿函数
④template T divides //除法仿函数
⑤template T modulus //取模仿函数
⑥template T negate //取反仿函数
3、示例
代码如下(示例):
#include<iostream>
#include<functional>
using namespace std;
//内建函数对象
//negate 算数仿函数 取反仿函数
void test01()
{
negate<int>n;
cout << n(50) << endl;
}
//plus 二元仿函数 加法
void tset02()
{
plus<int>p;
cout << p(10, 10) << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
三、关系仿函数
1、功能描述
实现关系对比
2、仿函数原型
①template bool equal_to //等于
②template bool not_equal_to / /等于
③template bool greater //大于
④template bool greater_equal //大于或等于
⑤template bool less //小于
⑥template bool less_equalr //小于或等于
3、示例
代码如下(示例):
#include<iostream>
#include<functional>
#include<vector>
#include<algorithm>
using namespace std;
//内建函数对象 关系仿函数
class MyCompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
void test01()
{
vector<int>v;
v.push_back(10);
v.push_back(30);
v.push_back(40);
v.push_back(20);
v.push_back(50);
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//降序
//sort(v.begin(), v.end(),MyCompare());
//greater<int>()内建的,直接用
sort(v.begin(), v.end(),greater<int>());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
四、逻辑仿函数
1、功能描述
实现逻辑运算
2、函数原型
①template bool logical_and //逻辑与
②template bool logical_or //逻辑或
③template bool logical_not //逻辑非
3、示例
#include<iostream>
#include<functional>
#include<vector>
#include<algorithm>
using namespace std;
//内建函数对象 逻辑仿函数
void test01()
{
vector<bool>v;
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;
//利用逻辑非 将容器v搬运到v2中,并执行取反操作
vector<bool>v2;
v2.resize(v.size());
transform(v.begin(), v.end(),v2.begin(), logical_not<bool>());
for (vector<bool>::iterator it = v2.begin(); it != v2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
五、总结
①使用内建函数对象,需要引入头文件#include
②逻辑反函数实际应用较少,了解即可