18.10 案例-员工分组

18.10 案例-员工分组

案例描述:

  • 公司招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在哪个部门工作
  • 员工信息有:姓名、工资组成;部门分为:策划、美术、研发
  • 随机给10名员工分配部门和工资
  • 通过multimap进行信息的插入key(部门编号)value(员工)
  • 分部门显示员工信息

实现步骤:

  • 创建10名员工,放到vector中
  • 遍历vector容器,取出每个员工,进行随机分组
  • 分组后,将员工部门编号作为key,具体员工作为value,放入到multimap容器中
  • 分部门显示员工信息
1、包含头文件
#include <iostream>
#include <map>
#include <vector>
#include <time.h>
#include <string>
using namespace std;
2、创建员工类

这里创建的很简单,因为用不到那么复杂的类。

class Worker
{
public:
	string name;
	int salary;
};
3、创建10个员工存入vector中

用一个单独的全局函数来完成这一过程,避免main里语句过多。
姓名格式:员工+字母
工资:随机

void creatWorker(vector<Worker>& v)
{
	string nameSeed = "ABCDEFGHIJKL";
	for (int i = 0; i < 10; i++)
	{
		Worker worker;
		worker.name = "员工";
		worker.name += nameSeed[i];
		worker.salary = rand() % 10000 + 10000;
		v.push_back(worker);
	}
}
4、将vector中的10个员工存入multimap中

key值为部门编号,value值为员工类。

void setGroup(const vector<Worker>& v, multimap<int, Worker>& m)
{
	for (vector<Worker>::const_iterator it = v.begin(); it != v.end(); it++)
	{
		int deptId = rand() % 3;
		m.insert(make_pair(deptId, *it));
	}
}
5、显示员工信息

大致思路:

  • 查找key值,获得迭代器
  • 查找key值的元素个数
  • 利用迭代器遍历,并且利用元素个数限制遍历次数
  • 如果不利于元素个数限制的话,或一致遍历完整个容器
void showWorkerByGroup(const multimap<int, Worker>&m)
{
	cout << "策划部门:" << endl;
	multimap<int, Worker>::const_iterator it = m.find(0);
	int num = m.count(0);
	int index = 0;
	for (; it != m.end() && index < num; it++, index++)
	{
		cout << "姓名:" << it->second.name << "\t工资:" << it->second.salary << endl;
	}
	cout << "---------------------------" << endl;
	
	cout << "美术部门:" << endl;
	it = m.find(1);
	num = m.count(1);
	index = 0;
	for (; it != m.end() && index < num; it++, index++)
	{
		cout << "姓名:" << it->second.name << "\t工资:" << it->second.salary << endl;
	}
	cout << "---------------------------" << endl;
	
	cout << "研发部门:" << endl;
	it = m.find(2);
	num = m.count(2);
	index = 0;
	for (; it != m.end() && index < num; it++, index++)
	{
		cout << "姓名:" << it->second.name << "\t工资:" << it->second.salary << endl;
	}
}
6、在main里实现全过程
int main()
{
	//重置随机函数
	srand((unsigned int)time(NULL));
	
	//创建员工
	vector<Worker>vWorker;
	creatWorker(vWorker);

	//员工分组
	multimap<int, Worker>mWorker;
	setGroup(vWorker, mWorker);

	//分组显示员工
	showWorkerByGroup(mWorker);
}
7、运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值