C++面向对象程序设计 044:编程填空:数据库内的学生信息 ---- (北大Mooc)


专题博客链接

北大C++ POJ课后习题博客全解记录


前引

初学C++ 对于这道题来说确实
我对继承和 一些细节的地方把控不是很好
这个解答是借鉴的 德林恩宝的代码
写完这道题后 北大Mooc所有的题也差不多宣告结束了
最后的魔兽世界我也写不动了
之后也就转载一下吧

这个也就当作 初涉C++
之后的每一天也要开始尝试用C++刷Leetcode了
不再用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;
}

猜你喜欢

转载自blog.csdn.net/qq_37500516/article/details/115057110