十二周(笔记)
12.1 multimap
- 用法
- multimap 容器里的元素,都是pair形式的
- multimap < T1,T2 >mp;
- mp里面的元素类型是 struct { T1 first; T2 second; };
- multimap中的元素按照first排序,并可以按first进行查找
- 缺省的排序规则是==“a.first < b.first” 为true==,则a排在b前面
- 实例
/*
学生成绩录入和查询系统
两种操作
1. Add name id score 添加学生信息
2. Query score 查询(输出已有记录中分数比score低的最高分获得者的信息,
如果有多个学生都满足条件就输出学号最大的那个学生,找不到满足条件的就输出"Nobody".
)
*/
#include <cstring>
#include <iostream>
#include <map> //使用multimap和map需要包含此头文件
using namespace std;
struct StudentInfo {
int id;
char name[20];
};
struct Student {
int score;
StudentInfo info;
};
typedef multimap<int, StudentInfo> MAP_STD;
//此后 MAP_STD 等价于 multimap <int,StudentInfo>
int main() {
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));
// make_pair生成一个 pair<int,StudentInfo>变量
//其first等于st.score,second 等于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;
for (; p != mp.begin() && p->first == score; p--) {
//遍历所有成绩和score相等的学生
if (p->second.id > maxId) {
maxp = p;
maxId = p->second.id;
}
}
if (p->first == score) {
//如果上面的循环是因为p==mp.begin()而终止,则p指向的元素还要处理
if (p->second.id > maxId) {
maxp = p;
maxId = p->second.id;
}
}
cout << maxp->second.name << " " << maxp->second.id << " "
<< maxp->first << endl;
} else {
// lower_bound的结果就是begin,说明没人分数比查询分数低
cout << "Nobody" << endl;
}
}
}
return 0;
}
/*
Add Jack 12 78
Query 78
Query 81
Add Percy 9 81
Add Marry 8 81
Query 82
Add Tom 11 79
Query 80
Query 81
*/