#include
#include
// #include <string.h>
// 定义结构体
struct Student {
char name[30];
int age;
float score;
};
// 定义比较函数,用于std::sort对结构体数组进行排序
bool compareStudentsByScore(const Student& a, const Student& b) {
return a.score > b.score;// 假设按照分数降序排序
}
// 输出结构体内容
void printStudent(const Student& student) {
std::cout << "Name: " << student.name << ", Age: " << student.age << ", Score: " << student.score << std::endl;
}
int main() {
// 初始化结构体数组
const int SIZE = 5;
Student students[SIZE] = {
{“Alice”, 20, 85.0},
{“Bob”, 22, 92.0},
{“Charlie”, 19, 78.0},
{“David”, 21, 85.0},
{“Eve”, 20, 88.0}
};
// 使用指针对结构体数组进行排序
std::sort(students, students + SIZE, compareStudentsByScore); // 使用指针遍历并输出排序后的结构体数组
for (Student* ptr = students; ptr < students + SIZE; ++ptr) { printStudent(*ptr);
} // 使用指针修改结构体成员的值
Student* ptrToModify = students + 2; // 指向第三个元素(下标为2)
ptrToModify->age += 1; // 将年龄加1
ptrToModify->score -= 0.5; // 将分数减去0.5 // 输出修改后的结构体
std::cout << "Modified student:" << std::endl;
printStudent(*ptrToModify); return 0;
}