#include <iostream>
#include <time.h>
#include <map>
#include <vector>
using namespace std;
class PersonItem {
friend void printMapPerson(map<int, PersonItem> &m);
private:
int num;
string name;
float score;
public:
PersonItem(){}
PersonItem(int num, string name, float score) {
this->num = num;
this->name = name;
this->score = score;
}
};
void printMapPerson(map<int, PersonItem> &m) {
map<int, PersonItem>::const_iterator it = m.begin();
for (; it != m.end() ; it++) {
cout << "key: " << (*it).first << " ==> " << (*it).second.num << " - "
<< (*it).second.name << " - " << (*it).second.score << endl;
}
}
void test01() {
map<int, PersonItem> m;
// 方式一写入方式
m.insert(pair<int, PersonItem>(103, PersonItem(103, "luck", 99.9f)));
//方式二写入方式(推荐)
m.insert(make_pair(101, PersonItem(101, "job", 77.7f)));
// 方式三写入方式
m.insert(map<int, PersonItem>::value_type(102, PersonItem(102, "tom", 666.4f)));
// 方式四. 这种方式不推荐,不会检查key是否存在,容易越界。
m[104] = PersonItem(104, "jack", 33.3f);
printMapPerson(m);
cout << "test01 end ..." << endl;
}
class Employee {
friend void employeeJoinDepartment(vector<Employee> &v, multimap<int, Employee> &m);
friend void showDepartEmployee(multimap<int, Employee> &m);
private:
string name;
int age;
int money;
string tel;
public:
Employee(){}
Employee(string name, int age, int money, string tel) {
this->name = name;
this->age = age;
this->money = money;
this->tel = tel;
}
};
void createVectorEmployee(vector<Employee> &v) {
int i;
string seedName = "ABCDE";
srand(time(NULL)); // 随机数设置随机种子.
for(i=0; i<5; i++) {
string tmpName = "员工";
tmpName += seedName[i];
int age = 20 + i;
int money = 15000 + rand() % 10 * 1000;
string tel = to_string(rand());
v.push_back(Employee(tmpName, age, money, tel));
}
}
// 员工加入部分函数.
void employeeJoinDepartment(vector<Employee> &v, multimap<int, Employee> &m) {
vector<Employee>::iterator it = v.begin();
for(; it != v.end(); it++) {
cout << "请输入 【" << (*it).name << "】 要加入的部门, 0(销售)、1(研发)、2(财务): ";
int op = 0;
cin >> op;
m.insert(make_pair(op, *it));
}
}
// 显示部门员工.
void showDepartEmployee(multimap<int, Employee> &m) {
cout << "请输入要显示的部门, 0(销售)、1(研发)、2(财务)" << endl;
int op = 0;
cin >> op;
switch (op) {
case 0:
cout << "--------销售部门员工如下-----------" << endl;
break;
case 1:
cout << "--------研发部门员工如下-----------" << endl;
break;
case 2:
cout << "--------财务部门员工如下-----------" << endl;
break;
}
// 寻找op的位置
multimap<int, Employee>::iterator ret;
ret = m.find(op);
if (ret == m.end()) {
return;
}
// 统计op的数量
int count = m.count(op);
// 从op的位置逐个遍历
for (int i = 0; i < count; i++, ret++) {
cout << "name: " << (*ret).second.name
<< " money: " << (*ret).second.money
<< " tel: " << (*ret).second.tel
<< " age: " << (*ret).second.age << endl;
}
}
void test02() {
// 创建5个员工 存放到vector
vector<Employee> v;
createVectorEmployee(v);
// 5个员工加入部门
multimap<int, Employee> m;
employeeJoinDepartment(v, m);
// 显示部门员工
showDepartEmployee(m);
cout << "test02 end ..." << endl;
}
int main() {
test01();
test02();
return 0;
}
网友评论