我有一个作业,我们必须设置一组学生,并按其学生ID对其进行排序,并显示其学生信息。考虑到结构和学生数组,我试图理解如何根据学生证的编号为学生定义排序功能
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
struct Student {
string name;
int stuID;
string email;
};
// Show the student information
void showAllInfo(Student *studentArray, int stuCount) {
cout << "Student Info: "<<endl <<endl<<
"\t\tStudent Name"<<"\t\tStudent ID"<<"\t\tStudent Email"<<endl<<endl ;
for (int i = 0; i < stuCount; i++)
{
cout<<"\t\t"<< studentArray[i].name<<"\t\t"<<studentArray[i].stuID<<"\t\t\t"<< studentArray[i].email<<endl;
}
cout << endl;
}
//Sort out the arrays for the student information
void sortInfo(Student *studentArray, int count){
}
int main() {
Student studentArray[4];
studentArray[0].name = "bob McBoberston";
studentArray[0].stuID = 01234;
studentArray[0].email = "bob@email.edu";
studentArray[1].name = "Shelby Donald";
studentArray[1].stuID = 01235;
studentArray[1].email = "bob@email.edu";
studentArray[2].name = "ronald mcdonald";
studentArray[2].stuID = 01236;
studentArray[2].email = "bob@email.edu";
studentArray[3].name = "bob McBoberston";
studentArray[3].stuID = 01237;
studentArray[3].email = "bob@email.edu";
int stuCount = 4;
return 0;
}
答案 0 :(得分:1)
这是使用std :: sort的简单实现: https://wandbox.org/permlink/lkF0xIx86I6HdoW2
实际排序只是:
sort(studentArray,studentArray+count,[](Student student1,Student student2){return student1.stuID < student2.stuID;});
要排序的前两个参数仅确定数组边缘在内存中的位置,而最后一个参数是lambda表达式(认为是小函数),sort函数在内部用于比较元素(即学生)。 / p>
答案 1 :(得分:-1)
是这样吗?:
for(int i = 0; i < numStudents; ++i)
{
//N^2 sort
for(int j = i + 1; j < numStudents; ++j)
{
//Sort by student ID
if(students[i].id < students[j].id)
{
//Swap (can also use std::swap, but assuming that's no good for your assignment
Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}