繁体   English   中英

使用指针数组排序

[英]Sorting using an array of pointers

因此,我将此结构称为具有成员字符串名称和int age的人。 基本上,我从文件中读取人员的姓名和年龄,然后将其放入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, count);

    for (int i = 0; i < 5; i++) {
        displayAPerson(cout, 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

按年龄排序后,没有任何变化。 当我按名称排序时,几个名称会切换,但不是全部。 我在这里做错了什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM