我正在尝试完成以下任务:
按字母顺序列出学生,按姓氏排序。 不要更改名称的给定大小写。 请勿更改输出文件格式。 (名字姓氏) 只需按姓氏打印记录,即
Annie J
Martin K
Toby L
这种类型必须按字母顺序排列(不仅仅是“词典”排序)。
数据是从文件中读取的,并通过虚拟函数传递,具体取决于该学生注册的课程。这就是我所拥有的。
for (int i = 1; i < numStudents; i++)
{
if (( list[i] -> getLastname() ) < ( list[i - 1] -> getLastname() ))
{
Student *temp = list[i - 1];
ist[i - 1] = list[i];
list[i] = temp;
}
}
我一直在研究这个问题已经有一段时间了,我担心自己已经错了。任何提示/指示赞赏!
答案 0 :(得分:1)
我假设您有一个类似的结构:
struct Student
{
std::string m_LastName;
std::string m_FirstName;
};
现在你需要确保你可以处理两个人姓氏相同的情况。在这种情况下,您需要查看名字。
bool NameCompare(const Student &name1, const Student &name2)
{
if(name1.m_LastName == name2.m_LastName) {
return name1.m_FirstName < name2.m_FirstName;
}
return name1.m_LastName < name2.m_LastName;
}
然后在您的学生列表中调用sort
std::list<Student> student_list;
// add some Student to the list
student_list.sort(NameCompare);
答案 1 :(得分:0)
使用字符串比较函数而不是您在此处使用的小于号:
if (( list[i] -> getLastname() ) < ( list[i - 1] -> getLastname() ))
此处还有类似的stackoverflow问题(部分)
Is string::compare reliable to determine alphabetical order?