处理学生信息(学号 姓名 性别 年龄)
要求:
1.输入I 10 wes f 23 插入一条学生记录
2.输入D 10删除一条学生记录
3.输出结果按学号从小到大排列
1.依次输入学生信息
#include <iostream>
#include <set>
using namespace std;
class student
{
public:
int num;
string name;
char sex;
int age;
// public://作为友元函数重载
friend bool operator < (student a,student b);//代表友元函数,友元函数是指某些虽然不是类成员却能够访问类的所有成员的函数。类授予它的友元特别的访问权。
};
bool operator < (student a,student b)
{
return a.num<b.num;
}
void display(multiset<student> v)
{
cout<<"结果:"<<endl;
multiset<student>::iterator it;
for(it=v.begin();it!=v.end();++it)
cout<<it->num<<" "<<it->name<<" "<<it->sex<<" "<<it->age<<endl;
}
main()
{
multiset<student> sset;
student t;
char cc;
while(1)
{
cout<<"请输入命令:"<<endl;
cin>>cc;
if(cc=='I')
{
cin>>t.num>>t.name>>t.sex>>t.age;
sset.insert(t);//默认排序准则是less
display(sset);
}
else if(cc=='D')
{
cin>>t.num;
sset.erase(t);
display(sset);
}
else
break;
}
}
/*
I 10 wes f 23
I 20 ert f 45
I 30 str m 89
D 10
*/
2.直接初始化
#include <iostream>
#include <string>
#include <set>
using namespace std;
struct student
{
int num;
string name;
char sex;
int age;
};
bool operator < (student a,student b)
{
return a.num<b.num;
}
void display(multiset<student> s)
{
cout<<"结果:"<<endl;
multiset<student>::iterator it;
for(it=s.begin();it!=s.end();++it)
cout<<"("<<it->num<<","<<it->name<<","<<it->sex<<","<<it->age<<")"<<endl;
//cout<<endl;
}
int main()
{
student stu[105],t;
multiset<student> s;
cout<<"初始化三条学生信息"<<endl;
for(int i=0;i<3;++i)
{
cin>>stu[i].num>>stu[i].name>>stu[i].sex>>stu[i].age;
s.insert(stu[i]);
}
multiset<student>::iterator it;
char cc;
while(1)
{
cout<<"请输入命令:"<<endl;
cin>>cc;
if(cc=='I')
{
cout<<"请输入学生信息:"<<endl;
cin>>t.num>>t.name>>t.sex>>t.age;
s.insert(t);
display(s);
}
else if(cc=='D')
{
cout<<"请输入学号:"<<endl;
cin>>t.num;
s.erase(t);
display(s);
}
else
break;
}
return 0;
}
/*
10 wes f 23
20 ert f 45
30 str t 89
I
12 rt f 67
D
10
*/