【C++STL容器篇之map—案例】

233 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

员工分组

案例描述

  • 公司今天招聘了10个员工(ABCDEFGHIJ),10名员工进入公司之后,需要指派员工在那个部门工作

  • 员工信息有: 姓名 工资组成;部门分为:策划、美术、研发

  • 随机给10名员工分配部门和工资

  • 通过multimap进行信息的插入 key(部门编号) value(员工)

  • 分部门显示员工信息

code

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <ctime>

using namespace std;

#define PARTONE 0
#define PARTTWO 1
#define PARTTHREE 2

class Worker
{
public:
    string m_Name;
    int m_Salary;
};

// 创建员工
void createWorkers(vector<Worker> &v)
{
    string nameSeed = "ABCDEFGHIJ";
    for (int i = 0; i < 10; i++)
    {
        Worker w;
        w.m_Name = "员工";
        w.m_Name += nameSeed[i];

        w.m_Salary = rand() % 10000 + 10000; // 10000 - 19999

        // 将员工添加到容器中
        v.push_back(w);
    }
}

//员工分组
void setGroup(vector<Worker> &v, multimap<int, Worker> &m)
{
    for (vector<Worker>::iterator it = v.begin(); it != v.end(); it++)
    {
        // 产生随机部门编号
        int depId = rand() % 3; // 0 1 2
        // 将员工插入到分组中
        // key为部门编号,value为具体员工
        m.insert(make_pair(depId, *it));
    }
}
//根据分组显示员工信息
void showWorkersByGroup(multimap<int, Worker> &m)
{
    cout << "===== 部门1 ===== " << endl;
    multimap<int, Worker>::iterator pos = m.find(PARTONE);
    int count = m.count(PARTONE);
    int index = 0;
    for (; pos != m.end() && index < count; pos++, index++)
    {
        cout << "姓名:" << pos->second.m_Name << ",薪水:" << pos->second.m_Salary << endl;
    }
    cout << endl;

    cout << "===== 部门2 ===== " << endl;
    pos = m.find(PARTTWO);
    count = m.count(PARTTWO);
    index = 0;
    for (; pos != m.end() && index < count; pos++, index++)
    {
        cout << "姓名:" << pos->second.m_Name << ",薪水:" << pos->second.m_Salary << endl;
    }
    cout << endl;

    cout << "===== 部门3 ===== " << endl;
    pos = m.find(PARTTHREE);
    count = m.count(PARTTHREE);
    index = 0;
    for (; pos != m.end() && index < count; pos++, index++)
    {
        cout << "姓名:" << pos->second.m_Name << ",薪水:" << pos->second.m_Salary << endl;
    }
    cout << endl;
}

int main()
{
    srand((unsigned int)time(NULL));
    // 1、创建员工
    vector<Worker> vWorkers;
    createWorkers(vWorkers);
    // 2、员工分组
    multimap<int, Worker> mWorkers;
    setGroup(vWorkers, mWorkers);

    // 3、分组显示员工
    showWorkersByGroup(mWorkers);

    return 0;
}