1. 案例描述
员工有salary和name属性,每个员工还有一个部门。本案例实现分部门显示员工信息。
2. 代码实现
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
class Worker
{
public:
string m_name;
int m_salary;
};
void push_worker(vector<Worker>&v)
{
string name_seed = "ABCDEFGHIJ";
for(int i=0; i<10; i++)
{
Worker w;
w.m_name = "worker";
w.m_name += name_seed[i];
int salary = rand() % 10000 +10000;
w.m_salary = salary;
v.push_back(w);
}
}
void set_group(vector<Worker>&v, multimap<int,Worker>&m)
{
for(vector<Worker>::iterator it=v.begin(); it!=v.end(); it++)
{
int partment_id = rand() % 3; // 0,1,2
m.insert(make_pair(partment_id, *it));
}
}
void show_partment(multimap<int,Worker>&m, int partment_id)
{
int num = m.count(partment_id);
int index = 0;
cout << "部门" << partment_id << "的员工信息" << endl;
for(multimap<int,Worker>::iterator pos=m.find(partment_id); pos!=m.end() && index < num; pos++, index++)
{
cout << "姓名:" << (*pos).second.m_name << ", 薪资:" << (*pos).second.m_salary << endl;
}
cout << endl;
}
int main()
{
vector<Worker>vWorker;
push_worker(vWorker);
multimap<int,Worker>mWorker;
set_group(vWorker, mWorker);
for(int i=0; i<3; i++)
{
show_partment(mWorker, i);
}
return 0;
}