例程:
/* 创建5个员工,给5个员工随机分配部门,然后按照部门打印员工*/
#include
#include
#include
class worker
{
public:
string mName;
int mAge;
};
void createVWorker(vector &vWorker)
{
string stringBase = “ABCDE”;
for (int i = 0; i < 5; i++)
{
worker p;
p.mName = “新员工”;
p.mName += stringBase[i];
p.mAge = rand() % 10 + 20;
vWorker.push_back§;
}
}
// 给员工分部门并保存到mapWorker容器中
void createGroupWorker(vector &vWorker, multimap<int, worker> &GroupWorker)
{
srand(time(NULL));
for (vector::iterator it = vWorker.begin(); it != vWorker.end(); it++)
{
int departmentID = rand() % 3 + 1;
switch (departmentID)
{
case SALEDEPARTMENT:
GroupWorker.insert(make_pair(departmentID, *it));
break;
case RDDEPARTMENT:
GroupWorker.insert(make_pair(departmentID, *it));
break;
case MEDEPARTMENT:
GroupWorker.insert(make_pair(departmentID, *it));
break;
default:
break;
}
}
}
// 打印函数
void printForDepartment(multimap<int, worker> &GroupWorker, int departmentID)
{
multimap<int, worker>::iterator Git = GroupWorker.find(departmentID);
int totalDepartNum = GroupWorker.count(departmentID);
int num = 0;
for (multimap<int, worker>::iterator it = Git; it != GroupWorker.end() && num < totalDepartNum; it++, num++)
{
cout << "员工姓名:" << (*it).second.mName << " 年龄:" << (*it).second.mAge << endl;
}
}
// 按照部门打印员工
void printGroupWorker(multimap<int, worker> &GroupWorker)
{
// multimap<int, worker>::iterator Git = GroupWorker.find(SALEDEPARTMENT);
// int totalDepartNum = GroupWorker.count(SALEDEPARTMENT);
// int num = 0;
// for (multimap<int, worker>::iterator it = Git; it!=GroupWorker.end() && num<totalDepartNum; it++, num++)
// {
// cout << “员工姓名:” << (*it).second.mName << " 年龄:" << (*it).second.mAge << endl;
// }
cout << “销售部门新员工:” << endl;
printForDepartment(GroupWorker, SALEDEPARTMENT);
cout << “研发部门新员工:” << endl;
printForDepartment(GroupWorker, RDDEPARTMENT);
cout << “ME部门新员工:” << endl;
printForDepartment(GroupWorker, MEDEPARTMENT);
}
void test05()
{
// 创建vector容器存放新来员工
vector vWorker;
// 创建multimap容器存放分了部门后的员工
multimap<int, worker> GroupWorker;
// 创建员工对象
createVWorker(vWorker);
// 给员工分部门并保存到mapWorker容器中
createGroupWorker(vWorker, GroupWorker);
// 按照部门打印员工
printGroupWorker(GroupWorker);
}
extern “C” void app_main(void)
{
test05();
}
结果:
在ESP32 CAM板子上调试通过
原始的例程: