void loadFromFile(const string& filename) { ifstream file(filename); string line; int number = 1; while (getline(file, line)) { float result = stof(line); Athlete* newAthlete = new Athlete{ number++, result, nullptr }; if (head == nullptr) { head = newAthlete; } else { Athlete* current = head; while (current->next != nullptr) { current = current->next; } current->next = newAthlete; } } }*/ void loadFromFile(const string& filename) { ifstream file(filename); string line; int number = 1; Athlete* current = new Athlete{ 0, 0, nullptr }; head = current; while (getline(file, line)) { float result = stof(line); Athlete* newAthlete = new Athlete{ number++, result, nullptr }; current->next = newAthlete; current = newAthlete; } current->next = nullptr; current = head; head = head->next; delete current; }改写成能读取文件所有数据并且排序
时间: 2024-02-10 18:09:11 浏览: 66
以下是改写后的代码:
```
void loadFromFile(const string& filename) {
ifstream file(filename);
string line;
vector<float> results;
while (getline(file, line)) {
float result = stof(line);
results.push_back(result);
}
sort(results.begin(), results.end());
int number = 1;
Athlete* current = new Athlete{ 0, 0, nullptr };
head = current;
for (float result : results) {
Athlete* newAthlete = new Athlete{ number++, result, nullptr };
current->next = newAthlete;
current = newAthlete;
}
current->next = nullptr;
current = head;
head = head->next;
delete current;
}
```
这里使用了一个 `vector` 来存储所有的结果,然后使用 `sort` 函数进行排序,最后再按照顺序构建链表。注意,原来的代码中没有进行排序,所以这里加了排序的步骤。
阅读全文