程序功能
Add:添加一个学生的名字,学号,成绩.
Query:查询比输入值小的最大成绩的学生信息,若有成绩相同的,则按学号大小输出.
本题很好的应用了lower_bound,multimap可以存储多个key值相同的特性.
样例输入:
Add Mike 13 78
Add Jack 12 78
Query 79
样例输出:
Mike 13 78
代码如下:
#include <iostream>
#include <map>
#include <string>
using namespace std;
class CStudent
{
public :
struct CInfo
{
int id;
string name;
};
int score;
CInfo info;
};
typedef multimap <int , CStudent :: CInfo> MAP_STD;
int main ()
{
MAP_STD mp;
CStudent st;
string cmd;
while (cin >> cmd)
{
if (cmd == "Add")
{
cin >> st.info.name >> st.info.id >> st.score ;
mp.insert (MAP_STD :: value_type (st.score , st.info));
}
else if (cmd == "Query")
{
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)
{
if (p->second.id > maxid)
{
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
cout << "Nobody" <<endl;
}
}
return 0;
}