网站系统源代码,中企动力科技股份有限公司西安分公司,关于网站建设的画册,网络营销产品的整体概念思路解读#xff1a; 定义结构体 Student: 结构体 Student 用来表示学生信息#xff0c;包含两个成员变量#xff1a;name#xff08;学生姓名#xff09;和 score#xff08;学生分数#xff09;。Student 结构体定义了一个构造函数#xff0c;用于初始化 name 和 sco…思路解读 定义结构体 Student: 结构体 Student 用来表示学生信息包含两个成员变量name学生姓名和 score学生分数。Student 结构体定义了一个构造函数用于初始化 name 和 score。 定义比较函数 compareStudents: 该函数用于比较两个 Student 对象的分数用于排序。比较函数返回 true 表示第一个学生的分数大于第二个学生实现降序排序。如果需要升序排序则可以修改比较条件为 a.score b.score。 在 main 函数中执行以下步骤: 创建一个 std::vectorStudent 容器来存储学生信息初始化时添加了四个学生对象。使用标准库函数 std::sort 对学生列表进行排序。std::sort 函数接收三个参数开始迭代器、结束迭代器和比较函数。这里使用 compareStudents 函数来按照分数进行降序排序。排序完成后遍历排序后的学生列表并输出每个学生的姓名和分数。
graph TDA[开始] -- B[定义 Student 结构体]B -- C[定义构造函数]C -- D[定义 compareStudents 比较函数]D -- E[在 main 函数中创建学生列表]E -- F[使用 std::sort 进行排序]F -- G[输出排序后的学生信息]G -- H[结束]
#include iostream
#include vector
#include algorithm
#include string// 定义学生信息结构体
struct Student {std::string name;int score;// 构造函数Student(const std::string name, int score) : name(name), score(score) {}
};// 比较函数用于按分数排序
bool compareStudents(const Student a, const Student b) {return a.score b.score; // 降序排序如果需要升序排序则使用a.score b.score
}int main() {// 创建学生信息列表std::vectorStudent students {{Alice, 90},{Bob, 85},{Charlie, 95},{David, 80}};// 使用标准库sort函数进行排序std::sort(students.begin(), students.end(), compareStudents);// 输出排序后的学生信息std::cout Sorted student list: std::endl;for (const auto student : students) {std::cout student.name : student.score std::endl;}return 0;
}