问题描述
因此,我将此结构称为具有成员字符串名称和整数年龄的人员。基本上,我从文件中读取人的姓名和年龄,并将其放入People对象的数组中。我有另一个指向该数组的数组。我正在尝试按年龄(选择排序)和姓名(冒泡排序)对人员进行排序,但似乎不起作用。
#include <iostream>
#include "proj1-person.hpp"
using namespace std;
int main()
{
Person thePeople[25];
Person *referencetoThePeople[25];
ifstream fileStream;
Person* tempPerson = new Person;
string newLine;
int count = 0;
fileStream.open("people.dat");
if (!fileStream) {
cout << "Error,not open" << endl;
}
else {
cout << "File open!" << endl;
}
while (getline(fileStream,newLine)) {
getAPersonFromStream(fileStream,tempPerson);
thePeople[count] = *tempPerson;
count++;
}
fileStream.close();
for (int i = 0; i < count; i++) {
referencetoThePeople[i] = &thePeople[i];
}
for (int i = 0; i < 5; i++) {
displayAPerson(cout,referencetoThePeople[i]);
}
cout << endl;
sortPersonArrayByAge(referencetoThePeople,count);
for (int i = 0; i < 5; i++) {
displayAPerson(cout,referencetoThePeople[i]);
}
cout << endl;
sortPersonArrayByName(referencetoThePeople,referencetoThePeople[i]);
}
cout << endl;
return 0;
}
istream &getAPersonFromStream(istream & fileStream,Person *tempPerson) {
getline(fileStream,(*tempPerson).name,',');
fileStream >> (*tempPerson).age;
return fileStream;
}
void sortPersonArrayByAge(Person** personArray,int arraySize) {
int min;
for (int i = 0; i < arraySize - 1; i++) {
min = i;
for (int j = i + 1; j < arraySize; j++) {
if ((*personArray)[j].age < (*personArray)[min].age) {
min = j;
}
swap(personArray[i],personArray[min]);
}
}
}
void sortPersonArrayByName(Person** personArray,int arraySize) {
for (int i = 0; i < arraySize - 1; i++) {
for (int j = 0; j < arraySize - i - 1; j++) {
if ((*personArray)[j].name > (*personArray)[j + 1].name) {
swap(personArray[j],personArray[j+1]);
}
}
}
}
void displayAPerson(ostream & outStream,const Person * tempPerson) {
outStream << (*tempPerson).name << "," << (*tempPerson).age << endl;
}
文件如下:
Bob Smith,19
Lucy Stephens,18
Meghan Lynn Padilla,20
Shakira,42
Nathan Austin,31
Jenna Harrison,101
按年龄排序后,没有任何变化。当我按名称排序时,几个名称会切换,但不是全部。我在这里做什么错了?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)