创建一个学生类链表,从stuArray.txt中读取对象数据,每读到一个对象数据,降序插入链表,学生类的大小比较按照 成绩之和排序,c++
时间: 2024-02-25 17:57:14 浏览: 22
好的,我理解了你的问题。以下是代码实现:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Student {
public:
string name;
int score1;
int score2;
int sum;
Student(string n, int s1, int s2) {
name = n;
score1 = s1;
score2 = s2;
sum = s1 + s2;
}
bool operator < (const Student& other) const {
return sum > other.sum;
}
};
class Node {
public:
Student* data;
Node* next;
Node(Student* s) {
data = s;
next = nullptr;
}
~Node() {
delete data;
}
};
class LinkedList {
public:
Node* head;
LinkedList() {
head = nullptr;
}
~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
void insert(Student* s) {
Node* newNode = new Node(s);
if (head == nullptr || *s < *head->data) {
newNode->next = head;
head = newNode;
}
else {
Node* current = head;
while (current->next != nullptr && *current->next->data < *s) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void print() {
Node* current = head;
while (current != nullptr) {
cout << current->data->name << " " << current->data->score1 << " " << current->data->score2 << endl;
current = current->next;
}
}
};
int main() {
ifstream inputFile("stuArray.txt");
if (!inputFile) {
cerr << "Cannot open file" << endl;
return 1;
}
LinkedList list;
string name;
int score1, score2;
while (inputFile >> name >> score1 >> score2) {
Student* s = new Student(name, score1, score2);
list.insert(s);
}
inputFile.close();
list.print();
return 0;
}
```
这里使用了链表来存储学生对象,并且在读取 stuArray.txt 文件时,将每个学生对象按照成绩之和的大小降序插入链表中。最后,打印链表中的学生对象。需要注意的是,在 `insert` 函数中,我们重载了 `<` 运算符,用于比较学生对象的大小。