c++ - 对二维结构数组进行排序

标签 c++ arrays sorting struct

<分区>

我正在尝试对二维结构数组(即每个结构都包含一个结构数组的结构数组)进行排序。我的代码对父结构和父内部的结构进行了正确排序。但是,当父结构交换到其正确位置时,其中的结构数组将重置为其原始顺序。

注意:学生姓名必须包含名字和姓氏(否则程序会崩溃)。等级也必须是大写的“A”、“B”、“C”、“D”或“F”。我必须使用我编写的排序算法(我选择了冒泡排序)。我不能使用 vector 或 sort() 函数等(这是作业)

Current Output:

Enter student name: Bob Chatter
Enter class title: Chem
Enter units for Chem: 3
Enter grade for Chem: A
Enter class title: Bio
Enter units for Bio: 3
Enter grade for Bio: B
Enter class title: Algebra
Enter units for Algebra: 4
Enter grade for Algebra: A
Enter class title:
Enter student name: Frank Brandon
Enter class title: Music
Enter units for Music: 3
Enter grade for Music: A
Enter class title:
Enter student name: Brad Anderson
Enter class title: CoSci
Enter units for CoSci: 3
Enter grade for CoSci: A
Enter class title:
Enter student name:
Student's name: Bob Chatter
Chem,A
Bio,B
Algebra,A
GPA: 3.70
Student's name: Frank Brandon
Music,A
GPA: 4.00
Student's name: Brad Anderson
CoSci,A
GPA: 4.00
Student's name: Brad Anderson
CoSci,A
GPA: 4.00
Student's name: Frank Brandon
Music,A
GPA: 4.00
Student's name: Bob Chatter
Chem,A
Bio,B
Algebra,A
GPA: 3.70
Press any key to continue . . .

Bob Chatters 的类(class)没有排序,当我调试时,它们会正确排序,直到学生按姓氏排序,此时类(class)的排序会重置。

#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <iomanip>
using namespace std;


struct Class
{
    string title; 
    int units;
    char grade;

};
struct Student
{
    string name;
    double gpa;
    Class classes[500];
};

int const SIZE = 50;
void initStudent(Student[], int);
void readStudent(Student[], int,  int&);
void gpaCalculate(Student&);
void print(Student[], int);
void stringToCharArray (string, char[]);
string returnLastName(string);
void sort_name(Student[], int);
void bubbleUpLastName(Student[],int, int);
void bubbleUpClass(Student[],int, int);
void swapStu(Student&, Student&);
void swapStusClass(Class&, Class&);


int main()
{   
    int numberOfStudents = 0;
    Student students[SIZE];
    initStudent(students, SIZE);
    readStudent(students, SIZE, numberOfStudents);

    for(int i = 0; students[i].name != "";i++)
        gpaCalculate(students[i]);
    print(students, numberOfStudents);
    sort_name(students, numberOfStudents);
    print(students, numberOfStudents);
    system("pause");
    return 0;
}
void initStudent(Student st[], int s)
{
    for(int i = 0; i < s; i++)
    {
        st[i].gpa = 0.0;
    }

}

void readStudent(Student st[], int s, int& nStus)
{
    for(int i = 0; i < s; i++)
    {   
        string tmpName;

        cout << "Enter student name: ";
        getline(cin, tmpName);
        if(tmpName == "")
            break;
        st[i].name = tmpName;
        nStus++;


        for(int j = 0; j < 500; j++)
        {   
            string tmpTitle;
            cout << "Enter class title: ";
            getline(cin, tmpTitle);
            if (tmpTitle == "")
                break;
            st[i].classes[j].title = tmpTitle;

            cout << "Enter units for " << st[i].classes[j].title << ": " ;
            cin >> st[i].classes[j].units;
            cout << "Enter grade for " << st[i].classes[j].title << ": " ;
            cin >> st[i].classes[j].grade;
            cin.ignore();
        }   
    }
}


void gpaCalculate (Student& s)
{
    double unitsByPoints = 0;
    double totalUnits = 0;

    for (int i = 0; s.classes[i].title != ""; i++)
    {

        int grade = 0;
        char ltrGrade = s.classes[i].grade;
        switch (ltrGrade)
        {
        case 'A':
            grade = 4;
                break;
        case 'B':
            grade = 3;
                break;
        case 'C':
            grade = 2;
                break;
        case 'D':
            grade = 1;
                break;
        case 'F':
            grade = 0;
                break;
        }
        unitsByPoints += s.classes[i].units*grade;
        totalUnits += s.classes[i].units;

    }
    s.gpa = unitsByPoints/totalUnits;
}

void print(Student st[], int size)
{

    for (int i = 0; i < size; i++)
    {
        cout << "Student's name: " <<  st[i].name << endl;
        for (int j = 0; st[i].classes[j].title != ""; j++)
        {
            cout << st[i].classes[j].title << "," << st[i].classes[j].grade << endl;
        }
        cout << fixed << setprecision(2) << "GPA: " <<  st[i].gpa << endl;
    }
}

// Returns the last name of the student passed in
string returnLastName(string s) 
{
    int i = 0;
    while (s[i] != ' ')
    {
        i++;
    }
    return s.substr(i + 1, s.length() - (i + 1));
}

 //sorts the students according to name and their classes according to their title
void sort_name(Student st[], int numValues)
{
    int stuCurrent = 0;
    int numClasses = 0;
    while (stuCurrent < numValues - 1)
    {   
        int classCurrent = 0;
        for(int i = 0; st[stuCurrent].classes[i].title != ""; i++)
        {
            numClasses = i;
        }
        while (classCurrent < numClasses)
        {
            bubbleUpClass(st,classCurrent,stuCurrent);
            classCurrent++;
        }


        bubbleUpLastName(st, stuCurrent, numValues-1);

            stuCurrent++;
    }
}

// Moves the student with the last name that should be first alphabeticaly into the first position of the Student array
void bubbleUpLastName(Student st[],int startIndex, int numValues) 
{
    for (int index = numValues; index > startIndex; index--)
    {   
        if ((returnLastName(st[index-1].name).compare(returnLastName(st[index].name)) > 0))
        {
            swapStu(st[index], st[index-1]);
        }
    }
}

// Moves the Class that should be first alphabeticaly (according to title) into the first position of the Class array
void bubbleUpClass (Student st[],int startIndex, int stuIndex)
{
    int numValues = 0;
    for(int i = 0; st[stuIndex].classes[i].title != ""; i++)
        numValues = i;
    for(int index = numValues; index > startIndex; index--)
    {
        if(st[stuIndex].classes[index - 1].title.compare(st[stuIndex].classes[index].title))
        {
            swapStusClass(st[stuIndex].classes[index], (st[stuIndex].classes[index - 1]));
        }
    }
}
void swapStu(Student& s1, Student& s2)
{
    Student tmp;
    tmp = s1;
    s1 = s2;
    s2 = tmp;
}

void swapStusClass(Class& c1, Class& c2)
{
    Class tmp;
    tmp = c1;
    c1 = c2;
    c2 = tmp;
}

/*



Define a structure called Class (with uppercase C) with the following data:
title, units and grade.

Define a structure called Student with the following data:
name (full name), gpa, and classes which is an array of Class structures (all the classes the student has taken so far).

Write an initialize function that receives an array of Student structures and its size and sets the gpa of all to 0.0.

In main, create 50 Students and call the above function to initialize the gpa for all 50 Students to 0.0. 

Then, pass the array of student structures and its size to a read function that will read student data from the user and store the entered data in the array of student structures.  The user will enter student name followed by the class title, units and grade received for each class he or she has taken.  When finished entering class information for a student, the user will just press Enter (an empty string) and to end entering more students, he or she will do the same for the student name. 

Example:

Enter student name: Maria Gomez

Enter class title: English 101
Enter units for English 101: 3 
Enter grade for English 101: A

Enter class title: Math 201
Enter units for Math 201: 4
Enter grade for Math 201: B

Enter class title: [User enters RETURN to indicate no more classes]

Enter student name: Kevin Duran

Enter class title: Poly Sci 101
Enter units for Poly Sci 101: 3 
Enter grade for Poly Sci 101: A

Enter class title: Math 201
Enter units for Math 201: 4
Enter grade for Math 201: B

Enter class title: [User enters RETURN to indicate no more classes]

Enter student name: [User enters RETURN to indicate no more students]

Once all Studnets have been entered, pass each element of the array of Student structures (element by element) to a gpa function which will compute and return the gpa for each Student using the classes array within each Student structure which contains the units and grade for each class taken by the student.  Store the gpa returned by the above function in the gpa member of the Student structures.  GPA is calculated by multiplying the number of units for each class by the points received for that class, and then adding all these products together and dividing it by total number of units.  The points received for a class is based on the grade: for A, it's 4; for B, it's 3; for C, it's 2; for D it's 1; and for F it's 0.  For example, if a student has take 3 classes with 3, 4, and 3 units and has received A, B, and C for these classes, respectively, then, the GPA will be 3 x 4 + 4 x 3 + 3 x 2 / 10 = 3.0.

Print all students showing name, followed by all classes taken, the grade received and the gpa using a display function which receives the array and its size as parameters.

Then, using a sort_name function, sort the student structures based on their last names and for each student, sort the classes he or she is taking based on class title.  Display the sorted list of students using the display function by calling it from main.

For example:

Kevn Duran
Poly Sci 101, A
Math 150, B
GPA: 3.0

Maria Gomez:
English 101, A
Math 201, C
GPA: 2.9

Robert Small
Comp Science 801, C
Comp Science 802, D
GPA: 1.9

Tom Wang
Comp Science 808, A
Comp Science 839, B
GPA: 3.5

Then, sort the students based on their GPA's using a sort_gpa function and print the list again using the display function. 

Then, ask what to search for - name or gpa.  If name is selected, read a student name from the user and, using a binary search function that takes the array, its size and the name to search for, finds the student and displays all of his or her information (name, gpa, units and list of classes taken).

Example:

Enter a student name:  Robert Small

Robert Small:
Comp Science 801, C
Comp Science 802, B
GPA: 2.5

If GPA is selected, read a GPA and using another binary search find the student with the given GPA by passing the students array, its size and the GPA to search for.  Display the name of the student with the specified GPA in main.  

Example:

Enter GPA to search for:  2.5

Robert Small was found with the GPA of 2.5

If the name or GPA is not found, tell the user it was not found; e.g.: There was no student with a GPA of 2.5; or Robert Small was not found.

Then, pass the array of student atructures and the size to a stats function which will return the average of the GPA's of all students and through two reference parameters will output the student structures that have the minimum and maximum GPA's.  Print the average GPA, as well as the names of the students who have the minimum and maximum GPA in main, like so:

Average GPA = 3.17

Robert Small has the minimum GPA of 2.5.

Tom Wang has the maximum GPA of 3.5. 

Finally, read a maximum and minimum GPA from the user and pass the array of student structures and its size, as well as two other arrays of student structures of the same size to a function which will store all students with a GPA of above the minimum in the highGPA array and all those with a GPA below the maximum in the lowGPA array.  Display the students stored in these two arrays by passing them each from main to the display function.  In other words, the highlow function receives two uninitalized arrays of student structures and populates them based on the GPA criteria passed to it (minimum GPA and maximum GPA).  Then, upon return to main, main passes each of these arrays to the display function to display them.  For example, if the user enters 2.0 for the maximum GPA, the lowGPA array gets filled out with all those students who have a GPA of less than 2.0.  Likewise, if the minimum GPA is 3.5, the highlow function populates the highGPA array with those students who have a GPA of 3.5 or higher.

Example:

Enter maximum GPA:  2.0

Enter minimum GPA:  3.5

Students with a GPA of lower than 2.0:

Robert Small 1.9

Students with a GPA of 3.5 or higher:

Tom Wang 3.5

When writing the highlow function, take advantage of the fact that the array elements are sorted based on the GPA, so to find all the students with a GPA of equal to or higher than the minimum GPA, it doesn't make sense to start from the first element in the array. Instead you can start from the midpoint. If the midpoint is lower than the minimum GPA, you can increment the index until the midpoint is no longer smaller and then all the GPA's from that point on will be larger and part of the high GPA's.  For low GPA's of course, you'd want to start from the beginning of the array and compare and store each that's lower than the maximum until they are no longer lower.

Functions you must write for this assignment (in addition to main):

initialize, read, display, sort_name, sort_gpa, search-name, search_gpa, stats, highlow.

Upload your cpp and exe files using the Browse and Upload buttons below and click Finish once both have been uploaded to the site.*/

是什么导致父结构中的结构数组被重置?

最佳答案

比较Class::title时你忘了添加比较来比较值:

你的线路:

if(st[stuIndex].classes[index - 1].title.compare(st[stuIndex].classes[index].title))

应该是:

if(0 < st[stuIndex].classes[index - 1].title.compare(st[stuIndex].classes[index].title))

我说你忘了 - 因为你在你的函数中有这个明确的比较来对学生进行排序。

现在解释你的结果:起初,只是偶然 - 一些学生的类(class)被排序,但在你的学生的位置发生变化(这是冒泡排序)并且下一次排序是在这些类(class)上完成的 - 所以因为实际上您不对类进行排序,而只是更改其位置,您可以在下一步中获得它们的原始顺序。


作为奖励,我建议不要使用比较进行排序 - 只需使用 operator < :

if(st[stuIndex].classes[index - 1].title < st[stuIndex].classes[index].title)

更简单,不是吗?

关于c++ - 对二维结构数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201680/

相关文章:

c++ - 鼠标滚轮的 Irrlicht 事件

c++ - 我可以从 __asm block 外部访问 __asm 变量吗?

c - 指针上的字符串 scanf

Java Map 按值排序

r - R中的排序列联表

algorithm - 针对部分排序的数据分析排序算法

c++ - 我可以通过重新播种结合 random_device 和 mt19937 生成加密安全随机数据吗?

c++ - 函数局部静态变量是否会阻止函数内联?

c++ - 为什么用 new 创建的 C++ 数组与 C 样式数组的行为不同?

java - 用新对象填充对象数组