特別ブログリンク
北京大学C ++ POJ授業後演習ブログ完全なソリューション記録
前引
C ++を学ぶ初心者は確かにこの質問
に向いています。私は継承と詳細があまり得意ではありません。
この回答は、Delin Enbaoのコードに基づいています。
この質問を書いた後、北京大学Moocのすべての質問はほぼ終わりです。
最終世界Warcraftの世界についてはもう書くことができません。後で
再版します。
これは、
C ++を使用してLeetcodeをC ++でブラッシングし始めてからの最初の日とも見なされます。Cを使用し
なくなった場合は、それに慣れて
から、最後にC ++ Primeを表示する必要があります。
元のタイトル
#include <iostream>
#include <string>
#include <map>
#include <iterator>
#include <algorithm>
using namespace std;
// 在此处补充你的代码
struct Student
{
string name;
int score;
};
template <class T>
void Print(T first,T last) {
for(;first!= last; ++ first)
cout << * first << ",";
cout << endl;
}
int main()
{
Student s[] = {
{
"Tom",80},{
"Jack",70},
{
"Jone",90},{
"Tom",70},{
"Alice",100} };
MyMultimap<string,int> mp;
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();
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;
}
コード
template<class key,class T,class Pred = greater<key> >
class MyMultimap:public multimap<key,T,Pred>
{
public:
void Set(key str,T score)
{
typename multimap<key, T, Pred>::iterator p1,p2;
p1 = multimap<key, T, Pred>::lower_bound(str) ;
p2 = multimap<key, T, Pred>::upper_bound(str);
for(;p1!= p2;p1++)
{
if(p1->first == str)
p1->second = score;
}
}
};
template<class T1,class T2>
ostream& operator <<(ostream& os,const pair<T1,T2> & p)
{
os<<'('<<p.first<<','<<p.second<<')';
return os;
}