问题:两个文本文件包含某中学的高考成绩,其中包含学生的准考证号、姓名、大学和总成绩。但两文件内内容有重复,现要求把两文本文件内容合并,去掉重复记录,并按准考证号升序排列输出。
#include <iostream>
#include <list>
#include <string>
#include <fstream>
#include <functional>
#include <algorithm>
#include <iterator>
#include <sstream>
using namespace std;
class Student
{
public:
Student(const string &id, const string &name, const string &university, const int &grade):
m_id(id), m_name(name), m_university(university), m_grade(grade){}
bool operator<(const Student &st)
{
return m_id < st.m_id;
}
bool operator==(const Student &st)
{
return m_id == st.m_id;
}
const string &GetId() const{return m_id;}
const string &GetName() const{return m_name;}
const string &GetUniversity() const{return m_university;}
const int &GetGrade() const{return m_grade;}
private:
string m_id;
string m_name;
string m_university;
int m_grade;
};
ostream &operator<<(ostream &os, const Student &st)
{
os << st.GetId() << "\t\t" << st.GetName() << "\t\t" << st.GetUniversity() << "\t\t" << st.GetGrade() <<endl;
return os;
}
class StudentMS
{
public:
bool AddStudent(const Student &st)
{
m_ls.push_back(st);
return true;
}
bool Merge(StudentMS &stms)
{
m_ls.sort();
stms.m_ls.sort();
m_ls.merge(stms.m_ls);
m_ls.unique();
return true;
}
void ShowStudent()
{
copy(m_ls.begin(), m_ls.end(), ostream_iterator<Student>(cout, ""));
}
private:
list<Student> m_ls;
};
void dealText(const string &path, StudentMS &stms)
{
ifstream is(path, ios::in);
if(!is) exit(1);
string str1, str2, str3, str4;
int sgrade;
while(!is.eof())
{
is >> str1 >> str2 >> str3 >> str4;
istringstream ist(str4);
ist >> sgrade;
Student st(str1, str2, str3, sgrade);
stms.AddStudent(st);
}
is.close();
}
int main()
{
StudentMS stms1;
StudentMS stms2;
dealText("F:/C++/C++FX_STL/STL/list1.txt", stms1);
dealText("F:/C++/C++FX_STL/STL/list2.txt", stms2);
stms1.Merge(stms2);
stms1.ShowStudent();
return 0;
}