C++進階實體2--員工分組
1 #include<iostream> 2 #include<map> 3 #include<vector> 4 #include<ctime> 5 using namespace std; 6 7 #define CEHUA 0 8 #define MEISHU 1 9 #define YANFA 2 10 11 // 員工分組 12 // 13 // 案例描述: 14 // 1. 10名員工(ABCDEFGHIJ) 15 // 2. 員工資訊:姓名,薪資組成;部門:策劃、沒熟、研發 16 // 3. 隨機給10名員工分配部門和薪資 17 // 4. 通過multimap進行資訊的插入,key(部門編號),value(員工) 18 // 5. 分部門顯示員工資訊 19 // 20 // 解決思路: 21 // 1. 創建10名員工,存入vector 22 // 2. 遍歷vector容器,取出每個員工,進行隨機分組 23 // 3. 分組后,將員工編號作為key,具體員工為value,存放到multimap容器中 24 // 4. 分部門顯示員工資訊 25 // 26 27 // 創建員工 28 class Worker 29 { 30 public: 31 string m_Name; 32 int m_Salary; 33 }; 34 35 void createWorker(vector<Worker>& v) { 36 37 string nameSeed = "ABCDEFGHIJ"; 38 for (int i = 0; i < 10; i++) { 39 Worker worker; 40 worker.m_Name = "員工"; 41 worker.m_Name += nameSeed[i]; 42 43 worker.m_Salary = rand() % 10000 + 10000; // 10000 ~ 19999; 44 45 v.push_back(worker); 46 } 47 48 } 49 50 // 員工分組 51 void setGroup(vector<Worker>& v, multimap<int, Worker>& m) { 52 for (vector<Worker>::iterator it = v.begin(); it != v.end(); it++) { 53 // 產生隨機部門編號 54 int depId = rand() % 3; // 0, 1, 2 55 56 // 將員工插入到分組中 57 // key表示部門編號,value表示具體員工 58 m.insert(make_pair(depId, *it)); 59 } 60 } 61 62 // 分組顯式 63 void showWorkerByGroup(multimap<int, Worker>&m) { 64 65 cout << "策劃部們:" << endl; 66 multimap<int, Worker>::iterator pos = m.find(CEHUA); 67 int count = m.count(CEHUA); // 統計具體人數 68 int index = 0; 69 for (; pos != m.end() && index < count; pos++, index++) { 70 cout << "姓名:" << pos->second.m_Name << " 薪資:" << pos->second.m_Salary << endl; 71 } 72 73 cout << "-----------------------" << endl; 74 cout << "美術部門:" << endl; 75 pos = m.find(MEISHU); 76 count = m.count(MEISHU); // 統計具體人數 77 index = 0; 78 for (; pos != m.end() && index < count; pos++, index++) { 79 cout << "姓名:" << pos->second.m_Name << " 薪資:" << pos->second.m_Salary << endl; 80 } 81 82 cout << "-----------------------" << endl; 83 cout << "研發部門:" << endl; 84 pos = m.find(YANFA); 85 count = m.count(YANFA); // 統計具體人數 86 index = 0; 87 for (; pos != m.end() && index < count; pos++, index++) { 88 cout << "姓名:" << pos->second.m_Name << " 薪資:" << pos->second.m_Salary << endl; 89 } 90 } 91 92 void test01() { 93 94 // 亂數 95 srand((unsigned int)time(NULL)); 96 97 // 1.創建員工 98 vector<Worker>vWorker; 99 createWorker(vWorker); 100 101 // 測驗員工資訊 102 //for (vector<Worker>::iterator it = vWorker.begin(); it != vWorker.end(); it++) { 103 // cout << "姓名:" << it->m_Name << " 工資:" << it->m_Salary << endl; 104 //} 105 106 // 2.員工分組 107 multimap<int, Worker>mWorker; 108 setGroup(vWorker, mWorker); 109 110 // 3.分組顯式員工 111 showWorkerByGroup(mWorker); 112 } 113 114 int main() { 115 116 test01(); 117 118 system("pause"); 119 120 return 0; 121 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471730.html
標籤:C++
