3.10.1 案例描述
- 公司今天招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在哪个部门工作
- 员工信息有:姓名,工资组成; 部门分为:策划、美术、研发
- 随机给10名员工分配部门和工资
- 通过multimap进行信息的插入 key(部门编号)value(员工)
- 分部门显示员工信息
3.10.2 实现步骤
- 创建10名员工,存放到vector
- 遍历vector,进行随机分组
- 分组后,将员工部门编号作为key,具体员工作为value,存放到multimap
- 分部门显示员工信息
3.10.3 代码
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <ctime>
using namespace std;
class Person
{
public:
string m_Name;
int m_Salary;
Person(string name, int money)
{
this->m_Name = name;
this->m_Salary = money;
}
};
void addEmployee(vector<Person>& v)
{
string nameside = "ABCDEFGHIJ";
for(int i = 0; i < 10; ++i)
{
string name = "员工_";
name += nameside[i];
int money = 10000 + rand() % 10000;
Person p(name, money);
v.push_back(p);
}
}
void setGroup(vector<Person>& v, multimap<int, Person>& mm)
{
srand((unsigned)time(NULL));
for(vector<Person>::iterator it = v.begin(); it != v.end(); ++it)
{
int index = 1 + rand() % 3;
mm.insert(make_pair(index, *it));
}
}
void showInfoByGroup(multimap<int, Person>& mm, map<int, string>& m)
{
for(multimap<int, Person>::iterator it = mm.begin(); it != mm.end(); ++it)
{
cout << "key = " << m[(*it).first] << " 姓名: " << (*it).second.m_Name
<< " 工资: " << (*it).second.m_Salary << endl;
}
cout << "策划部门: " << endl;
multimap<int, Person>::iterator pos = mm.find(1);
int count = mm.count(1);
int index = 0;
for(; pos != mm.end() && index < count; ++pos, ++index)
{
cout << "姓名: " << pos->second.m_Name
<< " 工资: " << pos->second.m_Salary << endl;
}
cout << "---------" << endl;
cout << "美术部门: " << endl;
pos = mm.find(2);
count = mm.count(2);
index = 0;
for(; pos != mm.end() && index < count; ++pos, ++index)
{
cout << "姓名: " << pos->second.m_Name
<< " 工资: " << pos->second.m_Salary << endl;
}
cout << "---------" << endl;
cout << "研发部门: " << endl;
pos = mm.find(3);
count = mm.count(3);
index = 0;
for(; pos != mm.end() && index < count; ++pos, ++index)
{
cout << "姓名: " << pos->second.m_Name
<< " 工资: " << pos->second.m_Salary << endl;
}
}
int main()
{
srand((unsigned)time(NULL));
vector<Person> v;
addEmployee(v);
multimap<int, Person> mm;
setGroup(v, mm);
map<int, string> m;
m.insert(make_pair(1, "策划"));
m.insert(make_pair(2, "美术"));
m.insert(make_pair(3, "研发"));
showInfoByGroup(mm, m);
}