【注意】multimap是对关键字first进行从小到大排序
用multimap进行插入的时候,用了make_pair.
mp.insert(make_pair(st.score, st.info))
make_pair生成了一个pair(int, StudentInfo)变量
其first等于st.score;
second等于st.info.
举一个简单的例子:
#include<iostream>
#include<map>
using namespace std;
int main()
{
multimap<int, string> mp;
int score;
string name;
int n;
cin >> n;
while(n--)
{
cin >> score >> name;
mp.insert(make_pair(score,name));
}
cout << mp.begin()->first << " " << mp.begin()->second << endl;
return 0;
}
本题完整代码:
#include<iostream>
#include<map>
using namespace std;
struct StudentInfo{
int id;
char name[20];
};
struct Student{
int score;//关键字,从小到大排序
StudentInfo info;
};
typedef multimap<int,StudentInfo> MAP_STD;//定义一个map的类型(first为int型,second为StudentInfo类型,后面就可以直接用Map_STD代替mutimap<int,StudentINfo>了
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
MAP_STD mp;
Student st;
char cmd[20];
while(cin >> cmd)
{
if(cmd[0] == 'A')
{
cin >> st.info.name >> st.info.id >> st.score;
mp.insert(make_pair(st.score,st.info));
}
else if(cmd[0] == 'Q')
{
int score;
cin >> score;
MAP_STD::iterator p = mp.lower_bound(score);//要按照关键字分数进行查找
if(p != mp.begin()) //有比他小的元素
{
-- p;
score = p->first;//比要查询分数低的最高分
MAP_STD::iterator maxp = p;
int maxId = p->second.id;
/*比如要查找的分数是比85分小的元素,mp中有4个84,所以需要比较id*/
for(; p != mp.begin() && p->first == score; --p)//遍历所有与score分数相等的学生
{
maxp = p;
maxId = p->second.id;
}
if(p->first == score)
{
if(p->second.id > maxId)
{
maxp = p;
maxId = p->second.id;
}
}
cout << maxp->second.name << " " << maxp->second.id << " " << maxp->first << endl;
}
else //p = mp.begin()说明一直找到开头都没找到比他小的元素
cout << "Nobody" << endl;
}
}
return 0;
}