1、需求:
2、代码实现
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<ctime>
#define CEHUA 0
#define MEISHU 1
#define YANFA 2
using namespace std;
class Worker
{
public:
string m_Name;
int m_Salary;
};
// 创建员工
void CreateWorker(vector<Worker>&w)
{
string strSeed = "ABCDEFGHJKX";
for (int i = 0; i < 10; i++)
{
Worker wk;
wk.m_Name = "员工";
wk.m_Name += strSeed[i];
wk.m_Salary = rand() % 10001 + 10000;
w.push_back(wk);
}
}
// 员工进行分组
void SetGroup(vector<Worker>&w,multimap<int,Worker>&m)
{
for (vector<Worker>::iterator it = w.begin(); it != w.end(); it++)
{
int depId = rand() % 3;
m.insert(make_pair(depId, *it));
}
}
// 按部门输出结果
void PrintValue(const multimap<int,Worker>&m)
{
cout << "策划部门:" << endl;
multimap<int, Worker>::const_iterator pos0 = m.find(CEHUA);
int sum0 = m.count(CEHUA);
int index0 = 0;
// map/multimap中的数据是按照从小到大的顺序进行排序的
for (; pos0 != m.end()&&index0<sum0; pos0++,index0++)
{
cout << "姓名:" << (*pos0).second.m_Name << " 薪资:" << pos0->second.m_Salary << endl;
}
cout << "--------------------------" << endl;
cout << "美术部门:" << endl;
multimap<int, Worker>::const_iterator pos1 = m.find(MEISHU);
int sum1 = m.count(MEISHU);
int index1 = 0;
for (; pos1 != m.end() && index1 < sum1; pos1++, index1++)
{
cout << "姓名:" << (*pos1).second.m_Name << " 薪资:" << pos1->second.m_Salary << endl;
}
cout << "-----------------------------------\n研发部门:\n";
multimap<int, Worker>::const_iterator pos2 = m.find(YANFA);
for (; pos2 != m.end(); pos2++)
{
cout << "姓名:" << (*pos2).second.m_Name << " 薪资:" << pos2->second.m_Salary << endl;
}
}
int main()
{
// 为了让随机数在每次都是随机的,需要添加随机数种子
srand((unsigned int)time(NULL));
// 创建员工的vector容器
vector<Worker>w;
CreateWorker(w);
// 创建员工分组
multimap<int, Worker>mp;
SetGroup(w, mp);
// 按部门来输出员工信息
PrintValue(mp);
system("pause");
}
结果如下: