我的理解,类似于set,连调用的函数的名字都是一样的,只是里面的元素的类型不一样,map里面所以的元素都是pair类型。所以插入的时候应该调用make_pair来转换类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//使用map和multimap时需要引入头文件<map> #include<iostream> #include<map> #include<cstring> using namespace std; struct studentinfo{ int id; char name[20]; }; struct student{ int score; studentinfo info; }; //这么定义的话,插入的时候元素会自动按multimap第一个元素(分数)排序 typedef multimap<int,studentinfo> map_std; int main(){ //multimap里面的元素都是pair的类型 //里面的元素按照first排序,并可以按first进行查找 map_std mp; student st; cout<<"请输入分数,id,姓名"<<endl; //读入 cin>>st.score>>st.info.id>>st.info.name; mp.insert(make_pair(st.score,st.info)); //输出 map_std::iterator p=mp.begin(); cout<<p->first<<endl; cout<<p->second.id<<" "<<p->second.name<<endl; //map类似于multimap这里不做学习 } |