C++容器--map_string

#include
#include
#include


using namespace std;


class Student
{
public:
Student(int id,string name,string grade)
{
this->id = id;
this->name = name;
this->grade = grade;
}
void print()
{
printf("id = %d,name = %s,grade = %s\n",id,name.c_str(),grade.c_str());
}
string getName()
{
return name;
}
private:
int id;
string name;
string grade;
};


class StudentManager
{
public:
//StudentManager(){}
~StudentManager()
{
multimap::iterator it = m.begin();
while(it != m.end())
{
delete it->second;
it = m.erase(it);
}
}
void add(int id,string name,string grade)
{
Student* ps = new Student(id,name,grade);
m.insert(make_pair(grade,ps));//返回值类型为pair<迭代器,bool>
}


void del(string name)
{
multimap::iterator it = m.begin();
while(it != m.end())
{
Student* ps = it->second;
if(ps->getName() == name)
{
it = m.erase(it);
delete ps;
}
else
it++;
}
}
void show()
{
multimap::iterator it = m.begin();
while(it != m.end())
{
it->second->print();
it++;
}
}
//分年级打印
void showGrade(string grade)
{
pair::iterator,multimap::iterator> ret = m.equal_range(grade);
multimap::iterator gStart = ret.first;
multimap::iterator gEnd = ret.second;
while(gStart != gEnd)
{
gStart->second->print();
gStart++;
}
}
private:
//键是年级,值是学生指针
multimap m;
};


int main()
{
StudentManager sm;
sm.add(1,"小明1","一年级");
sm.add(2,"小明2","三年级");
sm.add(4,"小明3","二年级");
sm.add(5,"小明4","三年级");
sm.add(6,"小明5","二年级");
sm.add(8,"小明6","三年级");
sm.add(7,"小明7","一年级");


sm.show();
cout << "------------" << endl;
sm.showGrade("一年级");


cout << "------------" << endl;
sm.showGrade("三年级");


sm.del("小明5");
cout << "------------" << endl;
sm.show();


return 0;
}

你可能感兴趣的:(C++容器--map_string)