我最近在学习容器,下面这个案例是我在学习得过程中看到的,看完之后自己敲了一遍,用了不太相同得办法,大致思路没有错,这个案例考验容器的使用,里面我使用了随机数,这里可以自己选择,算是自己做的小总结,适合初学者
案例介绍
- 公司今天招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在那个部门工作
- 员工信息有: 姓名 工资组成;部门分为:策划、美术、研发
- 随机给10名员工分配部门和工资
- 通过multimap进行信息的插入 key(部门编号) value(员工)
- 分部门显示员工信息
#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<ctime>
#include<map>
#define CEHUA 0
#define MEISHU 1
#define YANFA 2
class Woker{
public:
string m_name;
int m_salary;
};
// 创建对象的函数
void createWoker(vector<Woker>&Wokers){
Woker woker;
string nameseed = "ABCDEFGHIJ";
string name;
for(int i=0;i<nameseed.size();i++){
name = "员工";
name += nameseed[i];
woker.m_name = name;
woker.m_salary = rand()%10001 + 10000; // 取值是10000~20000
Wokers.push_back(woker);
}
}
// 打印员工信息
void printWoker(vector<Woker>&woker){
for(vector<Woker>::iterator it = woker.begin();it!=woker.end();it++){
cout<<it->m_name<<"的工资为:"<<it->m_salary<<endl;
}
}
// 对员工进行分组
void setwokers(multimap<int,Woker>&m,vector<Woker> &v){
int deptId; // 部门编号
for(vector<Woker>::iterator it=v.begin();it!=v.end();it++){
deptId = rand() % 3; // 0 1 2
m.insert(make_pair(deptId,(*it)));
}
}
// 显示以员工分组
void showWokerByGroup(multimap<int,Woker> &m){
cout<<"策划部:"<<endl;
int count = m.count(CEHUA); // 统计总数
int index = 0; // 计算每次的总数
multimap<int,Woker>::iterator pos = m.find(CEHUA);
while(pos != m.end() && index <count){
cout<<"姓名:"<< pos->second.m_name<<" 工资:"<<pos->second.m_salary<<endl;
pos++;
index++;
}
cout<<"-----------------------------"<<endl;
cout<<"美术部:"<<endl;
count = m.count(MEISHU); // 统计总数
index = 0; // 计算每次的总数
pos = m.find(MEISHU);
while(pos != m.end() && index <count){
cout<<"姓名:"<< pos->second.m_name<<" 工资:"<<pos->second.m_salary<<endl;
pos++;
index++;
}
cout<<"-----------------------------"<<endl;
cout<<"研发部:"<<endl;
count = m.count(YANFA); // 统计总数
index = 0; // 计算每次的总数
pos = m.find(YANFA);
while(pos != m.end() && index <count){
cout<<"姓名:"<< pos->second.m_name<<" 工资:"<<pos->second.m_salary<<endl;
pos++;
index++;
}
}
void test01(){
vector<Woker> wokers;
// 创建员工对象
createWoker(wokers);
// 打印输出员工
// printWoker(wokers);
// 员工分组
multimap<int,Woker> mwoker;
setwokers(mwoker,wokers);
// 分组显示员工
showWokerByGroup(mwoker);
}
int main(){
// 添加一个随机种子
srand((unsigned int)time(NULL));
test01();
return 0;
}