一个学生成绩录入和查询系统,接受以下两种输入:
Add name id score
Query score
name是个不超过16字符的字符串,中间没有空格,代表学生姓名。id
是个整数,代表学号。score是个整数,表示分数。学号不会重复,分数
和姓名都可能重复。
两种输入交替出现。第一种输入表示要添加一个学生的信息,碰到这
种输入,就记下学生的姓名、id和分数。第二种输入表示要查询,碰到这
种输入,就输出已有记录中分数比score低的最高分获得者的姓名、学号
和分数。如果有多个学生都满足条件,就输出学号最大的那个学生的信
息。如果找不到满足条件的学生,则输出“Nobody”
#include <iostream>
#include <map> //使用multimap和map需要包含此头文件
#include <cstring>
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>
// typedef int * PINT;
// 则此后 PINT 等价于 int *。 即 PINT p; 等价于 int * p;
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;
}
//lower_bound的结果就是 begin,说明没人分数比查询分数低
else cout << "Nobody" << endl;
}
}
return 0;
}
为什么要新建一个maxp的迭代器不直接用P呢?感觉这两个最后的结果都是一样的.
maxp只是用来保存满足 (p->first == score 并且 p->second.id > maxId)这个特定条件是的迭代器,而p是用来遍历map的,p不管满不满足条件,是从map尾一直遍历到begin()的(也可能不到begin())。就相当于maxp是用来记录最大值的,p是用来遍历的。作用不一样。