所以我必须允许用户使用5种不同类型的信息创建一定数量的结构,然后根据其中一种类型进行排序。例如,他们会输入所有数据,然后按等级或名称排序。我如何在不同的结构中创建一个只有不同名称或等级的数组呢?
#include <iostream>
#include <string>
struct student
{
std::string studentName;
std::string studentIDNumber;
int currentExamGrade;
int priorExamGrade;
double GPA;
};
void createStudent()
{
int numStudents;
std::cout << "Enter number of students\n";
std::cin >> numStudents;
while (numStudents > 0)
{
student name;
std::cout << "Enter the student's name\n";
std::cin >> name.studentName;
std::cout << "Enter the student's ID number\n";
std::cin >> name.studentIDNumber;
std::cout << "Enter the student's current exam grade\n";
std::cin >> name.currentExamGrade;
std::cout << "Enter the student's prior exam grade\n";
std::cin >> name.priorExamGrade;
std::cout << "Enter the student's GPA\n";
std::cin >> name.GPA;
numStudents -= 1;
}
}
int main()
{
createStudent();
int choice;
std::cout << "How do you want to sort the list?\n (Enter 1 for name, 2 for ID number, 3 for current exam grade, 4 for prior exam grade, 5 for GPA\n";
std::cin >> choice;
return 0;
}
答案 0 :(得分:0)
确定。我假设你不知道C ++中的内置排序函数。看看std::sort()
接受输入:
input values into struct array + printing out
现在制作一个结构数组:
How do you make an array of structs in C?
Creating an array of structs in C++
现在对这些数组进行排序:
Sorting a vector of custom objects
如何解决此问题:
std::sort()
允许您根据哪些非生活对象进行比较来提供自定义函数。一个这样的功能的例子是:
bool gpa_comparision_function (student s1,student s2)
{
return s1.GPA < s2.GPA;
}
需要通过排序函数比较2个学生的参数,并根据GPA返回学生s1和s2的顺序。
这就是声明s1.GPA < s2.GPA
很重要的原因。
因此,如果学生 s1的GPA = 5.0 且 s2的GPA = 4.0 ,我们希望订单为s2,s1(升序),因此功能返回false,说明s2应该在s1之前。
所以在调用排序函数时:
sort (arr_of_students,arr_of_students+N,gpa_comparision_function);
注意第三个参数gpa_comparision_function
,这告诉内置函数使用我们的比较函数。
谈话很便宜,请告诉我代码:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct student
{
std::string studentName;
std::string studentIDNumber;
int currentExamGrade;
int priorExamGrade;
double GPA;
};
bool gpa_comparision_function (student s1,student s2)
{
return s1.GPA < s2.GPA;
}
bool currentExamGrade_comparision_function (student s1,student s2)
{
return s1.currentExamGrade < s2.currentExamGrade;
}
int main ()
{
// Create an array of structs
student arr_of_students[100]; // A better way will be vector<student>
// Take input
// ...
// Now lets sort, assuming number of students is N
// Based on GPA
sort (arr_of_students,arr_of_students+N,gpa_comparision_function);
// Based on currentExamGrade
sort (arr_of_students,arr_of_students+N,currentExamGrade_comparision_function);
return 0;
}