14 STL函数对象
14.1函数对象
①概念:
- 重载函数操作符的类,其对象常称为函数对象
- 函数对象使用重载()时,行为类似函数调用,也叫仿函数
本质:
- 函数对象(仿函数)是一个类,不是一个函数
②函数对象的使用
特点:
- 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
- 函数对象超出普通函数的概念,函数对象可以有自己的状态
- 函数对象可以作为参数传递
测试代码:
/*
公司今天招聘了10个员工(ABCDEFGHI,10名员工进入公司之后,需要指派员工在那个部门工作
员工信息有 : 姓名 工资组成,部门分为 : 策划、美术、研发
。随机给10名员工分配部门和工资
。通过multimap进行信息的插入 key(部门编号) value(员工)
。分部门显示员工信息
*/
/*
* 1.用vactor容器存放10名员工信息,
* 2.通过multimap进行信息的插入 key(部门编号) value(员工)
* 3.写一个函数分部门显示员工信息
*/
#include<iostream>
using namespace std;
class MyAdd
{
public:
int operator()(int v1, int v2)
{
return v1 + v2;
}
};
//1.函数对象在使用时可以像普通函数那样调用,可以有参数,可以有返回值
void test01()
{
MyAdd myadd;
cout << "myadd(10,10)=" << myadd(10, 10) << endl;
}
//2.函数对象超出普通函数的概念,函数对象可以有自己的状态
class MyPrint
{
public:
MyPrint()
{
this->count = 0;
}
void operator()(string test)
{
cout << test << endl;
count++;
}
int count; //内部自己状态
};
void test02()
{
MyPrint myPrint;
myPrint("hello world");
myPrint("hello world");
myPrint("hello world");
cout << "myPrint调用次数为:" <<myPrint.count<< endl;
}
//3.函数对象可以作为参数传递
void doPrint(MyPrint& mp, string test)
{
mp(test);
}
void test03()
{
MyPrint myPrint;
doPrint(myPrint, "hello c++");
}
int main()
{
//test01();
//test02();
test03();
return 0;
}
14.2 谓词
- 返回bool类型的仿函数称为谓词
- 如果operator()接受一个参数,那么叫做一元谓词
- 如果operator()接受两个参数,[那么叫做二元谓词
一元谓词测试:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class GreaterFive
{
public:
bool operator()(int val)
{
return val > 5;
}
};
void test01()
{
vector<int >v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//查找容器中 有没有大于5的数字
//GreaterFive()创建匿名函数对象
vector<int>::iterator it= find_if(v.begin(), v.end(), GreaterFive());
if (it == v.end())
cout << "未找到" << endl;
else
cout << "找到了大于5的数字为: " << *it << endl;
}
int main()
{
test01();
return 0;
}
二元谓词测试:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<time.h>
using namespace std;
class MyCompare
{
public:
bool operator()(int va1, int va2)
{
//降序排列
return va1 > va2;
}
};
void test01()
{
srand((int)time(0));
vector<int> v;
for (int i = 0; i < 10; i++)
{
v.push_back(rand() %100);
}
sort(v.begin(), v.end());
//升序排序
for (vector<int >::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
sort(v.begin(), v.end(), MyCompare());
//降序排序
for (vector<int >::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}