题目:
OpenJudge - 044:编程填空:数据库内的学生信息
分析:
这道题虽然是MyMultimap,但主要是考察继承类和multimap,一开始是想到了用multimap去套,但没想到要用继承,自己写了半天的函数,时间不说还报错(哭晕在厕所。。。)后来参考一些博主的题解才发现直接用继承关系= =。
还有一点是要清楚map或者multimap里面每一个元素是一个pair<class a,class b>,这样在print的时候就知道形参是 pair<class a,class b>类型的。
用了继承之后,就只有一个Set函数需要我们来写,也是map/multimap的基本应用。
参考代码:
#include <iostream>
#include <string>
#include <map>
#include <iterator>
#include <algorithm>
using namespace std;
// 在此处补充你的代码
template <class key, class T, class _cmp =std::greater<key> >
class MyMultimap:public multimap<key,T,_cmp>{ //直接用继承关系,秒啊
public:
void Set(key _key,T _new){
typename multimap<key,T,_cmp>::iterator p,q;
p = this->lower_bound(_key);
q = this->upper_bound(_key);
while(p != q){
if(p->first == _key){
p->second = _new;
}
p++;
}
}
};
template<class T1,class T2>
ostream & operator<<(ostream & out, const pair<T1,T2> & p){
out << '(' << p.first << ',' << p.second << ')';
return out;
}
struct Student
{
string name;
int score;
};
template <class T>
void Print(T first,T last) {
for(;first!= last; ++ first)
cout << * first << ","; //overload "<<"
cout << endl;
}
int main()
{
Student s[] = { {"Tom",80},{"Jack",70},
{"Jone",90},{"Tom",70},{"Alice",100} };
MyMultimap<string,int> mp; //建立模版类MyMultimap
for(int i = 0; i<5; ++ i)
mp.insert(make_pair(s[i].name,s[i].score));
Print(mp.begin(),mp.end()); //按姓名从大到小输出
mp.Set("Tom",78); //把所有名为"Tom"的学生的成绩都设置为78
Print(mp.begin(),mp.end());
MyMultimap<int,string,less<int> > mp2;
for(int i = 0; i<5; ++ i)
mp2.insert(make_pair(s[i].score,s[i].name));
Print(mp2.begin(),mp2.end()); //按成绩从小到大输出
mp2.Set(70,"Error"); //把所有成绩为70的学生,名字都改为"Error"
Print(mp2.begin(),mp2.end());
cout << "******" << endl;
mp.clear();//MyMultimap.clear();
string name;
string cmd;
int score;
while(cin >> cmd ) {
if( cmd == "A") {
cin >> name >> score;
if(mp.find(name) != mp.end() ) {
cout << "erroe" << endl;
}
mp.insert(make_pair(name,score));
}
else if(cmd == "Q") {
cin >> name;
MyMultimap<string,int>::iterator p = mp.find(name);
if( p!= mp.end()) {
cout << p->second << endl;
}
else {
cout << "Not Found" << endl;
}
}
}
return 0;
}
注:以上代码虽然通过了OpenJudge的样例测试,但受限于本人水平,如有疏漏,恳请斧正。