知识点1【map容器】
map容器 键值 和 实值 是分开的
Map 的特性是,所有元素都会根据元素的键值自动排序。
map容器 键值必须唯一。
#include <iostream>
#include <map>
using namespace std;
void printMapIntString(map<int,string> &m)
{
map<int,string>::iterator it=m.begin();
for(;it!=m.end();it++)
{
//*it == <int,string>
cout<<(*it).first<<" "<<(*it).second<<endl;
}
}
void test01()
{
map<int,string> m;
m.insert(pair<int,string>(10086,"移动"));
m.insert(make_pair(10010,"联通"));//推荐
m.insert(map<int,string>::value_type(10000,"电信"));
//9527key值 m[key]实值
m[9527]="星爷";
printMapIntString(m);
cout<<m[10086]<<endl;
}
知识点2【multimap容器】
知识点2【multimap案例】
公司今天招聘了 5 个员工,5 名员工进入公司之后,需要指派员工在那个部门工作
人员信息有: 姓名 年龄 电话 工资等组成 通过 Multimap 进行信息的插入 保存 显示 分部门显示员工信息 显示全部员工
#include <iostream>
#include<map>
#include<string>
#include<vector>
using namespace std;
#define SALE_DEPATMENT 1 //销售部门
#define DEVELOP_DEPATMENT 2 //研发部门
#define FINACIAL_DEPATMENT 3 //财务部门
#define ALL_DEPATMENT 4 //所有部门
class Person
{
public:
string name;
int age;
double salary;
string tel;
};
void createVectorPeerson(vector<Person> &v)
{
int i=0;
string seed="ABCDE";
for(i=0; i<5; i++ )
{
Person p;
p.name = "员工";
p.name += seed[i];
p.age = rand() % 30 + 20;
p.salary = rand() % 20000 + 10000;
p.tel = "010-8888888";
v.push_back(p);
}
}
void personByGroup(vector<Person> &v, multimap<int,Person> &m)
{
vector<Person>::iterator it = v.begin();
for(;it!=v.end(); it++)
{
//*it == Person
cout<<(*it).name<<" "<<(*it).age<<" "<<(*it).salary<<" "<<(*it).tel<<endl;
while(1)
{
cout<<"请选择加入的部门1(销售)、2(研发)、3(财务):";
int ch=0;
cin>>ch;
if(ch==1 || ch ==2 || ch==3)
{
m.insert(make_pair(ch, *it));
break;
}
else
{
cout<<"输入有误请重新输入"<<endl;
}
}
}
}
void showMapPerson(multimap<int,Person> &m, int op)
{
switch(op)
{
case 1:
cout<<"销售部门员工信息如下:"<<endl;
break;
case 2:
cout<<"研发部门员工信息如下:"<<endl;
break;
case 3:
cout<<"财务部门员工信息如下:"<<endl;
break;
}
multimap<int,Person>::iterator ret;
ret = m.find(op);
if(ret != m.end())//找到
{
//统计key值的个数
int n = m.count(op);
int i=0;
for(i=0;i<n;i++, ret++)
{
//*ret == <int,Person>
cout<<"\t"<< (*ret).second.name<<" "<<(*ret).second.age<<" "<<\
(*ret).second.salary<<" "<<(*ret).second.tel<<endl;
}
}
}
int main(int argc, char *argv[])
{
//定义一个vector存放5人
vector<Person> v;
createVectorPeerson(v);
//将5人添加到不同的部门中
multimap<int,Person> m;
personByGroup(v, m);
//查看部门的员工信息
showMapPerson(m, 1);
showMapPerson(m, 2);
showMapPerson(m, 3);
return 0;
}