3.10.1 案例描述
公司今天招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在那个部门工作
员工信息有: 姓名 工资组成;部门分为:策划、美术、研发
随机给10名员工分配部门和工资
通过multimap进行信息的插入 key(部门编号) value(员工)
分部门显示员工信息
3.10.2 实现步骤
- 创建10名员工,放到vector中
- 遍历vector容器,取出每个员工,进行随机分组
- 分组后,将员工部门编号作为key,具体员工作为value,放入到multimap容器中
- 分部门显示员工信息
#include<iostream>
#include<vector>
#include<ctime>
#include<map>
#define cehua 0
#define meishu 1
#define yanfa 2
using namespace std;
//公司今天招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在那个部门工作
//员工信息有 : 姓名 工资组成;部门分为:策划、美术、研发
//随机给10名员工分配部门和工资
//通过multimap进行信息的插入 key(部门编号) value(员工)
//分部门显示员工信息
//解析思路
/*
用vector创建员工,存放员工信息,用类存放,
用编号存放信息,例如1编号存放美术部门的员工,multimap(insert(i,Person))
显示员工分部门,先找到部门的编号通过find找到返回迭代器,通过编号输出,通过迭代器输出内容
*/
class Person
{
public:
string name;
int salary;
};
void createPerson(vector<Person>& v)
{
string seed = "ABCDEFGHIJ";
for (int i = 0; i < 10; i++)
{
Person s1;
s1.name += seed[i];
s1.salary = rand() % 10000 + 10000; //10000-19999
v.push_back(s1);
}
}
void setPerson(vector<Person>& v,multimap<int,Person>&m)
{
for (vector<Person>::iterator it = v.begin(); it != v.end();it++) {
int i = rand() % 3; //用编号存放部门
m.insert(make_pair(i, *it));
}
}
void showPerson(vector<Person>&v, multimap<int, Person>& m)
{
//通过编号输出员工信息
cout << "策划部门:" << endl;
multimap<int, Person>::iterator pos = m.find(cehua); //先通过策划找到迭代器的位置
int count = m.count(cehua); //cehua 编号的数量
int index = 0; //输出计数
for (; pos != m.end() && index < count; index++, pos++)
{
cout << "姓名: " << pos->second.name << " 薪资: " << pos->second.salary << endl;
}
cout << "----------------------" << endl;
//通过编号输出员工信息
cout << "美术部门:" << endl;
pos = m.find(meishu); //先通过策划找到迭代器的位置
count = m.count(meishu); //cehua 编号的数量
index = 0; //输出计数
for (; pos != m.end() && index < count; index++, pos++)
{
cout << "姓名: " << pos->second.name << " 薪资: " << pos->second.salary << endl;
}
cout << "----------------------" << endl;
//通过编号输出员工信息
cout << "研发部门:" << endl;
pos = m.find(yanfa); //先通过策划找到迭代器的位置
count = m.count(yanfa); //cehua 编号的数量
index = 0; //输出计数
for (; pos != m.end() && index < count; index++, pos++)
{
cout << "姓名: " << pos->second.name << " 薪资: " << pos->second.salary << endl;
}
cout << "----------------------" << endl;
}
int main()
{
srand((unsigned int)time(NULL));
vector<Person> v;
multimap<int, Person> m;
createPerson(v);
setPerson(v, m);
showPerson(v,m);
return 0;
}