2012-11-02 3 views
1

2 차원 구조체 배열 (즉, 각 구조체에 구조체 배열이 들어있는 구조체 배열)을 정렬하려고합니다. 내 코드는 부모 구조체와 부모 구조체를 올바르게 정렬합니다. 그러나 부모 구조체를 올바른 위치로 스왑하면 구조체 배열이 원래 순서로 다시 설정됩니다.2 차원 구조체 배열 정렬

참고 : 학생 이름은 이름과 성을 포함해야합니다 (또는 프로그램이 중단됩니다). 또한 학점은 반드시 "A", "B", "C", "D"또는 "F"여야합니다. 나는 (나는 버블 정렬을 선택했다) 쓰는 정렬 알고리즘을 사용해야한다. 나는 벡터 또는 종류() 등의 함수 (이 숙제입니다) 나는 학생들이 성을 기준으로 분류 될 때까지 제대로 분류되어 디버깅 할 때

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 . . . 

밥 웨이브 소음 클래스가, 정렬되지 않습니다 사용할 수있는 Classes reset의 정렬을 가리 킵니다.

#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를 비교할 때

+1

질문이 있으십니까? –

+0

부모 구조체 내부의 구조체 배열이 초기화되는 원인은 무엇입니까? – Zzz

+0

잘못된 출력을 생성한다고 생각되는 가장 간단한 입력을 보여줍니다. 출력과이 예제의 예상 출력도 함께 표시하십시오. – PiotrNycz

답변

1

비교하려면 비교를 추가하는 것을 잊었다 값 :

귀하의 라인 :

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)) 

난 당신이 잊고 말 - 당신이 명시을 가지고 있기 때문에 귀하의 기능을 비교하여 학생들을 분류하십시오.

결과에 대한 설명 : 처음에는 우연히 만난 학생의 수업이 정렬되었지만 학생의 위치가 바뀌면 (거품 형) 다음 수업이 이루어집니다. 실제로 클래스를 정렬하지 않고 위치 만 변경하면 다음 단계에서 원래 시퀀스를 가질 수 있습니다. 보너스 I 조언으로


하지 정렬에 비교 사용하기 - 단지 operator < 사용

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

훨씬 간단, 안 그래?

+0

도움을 주셔서 감사합니다. 저는 훨씬 더 복잡한 것을 찾고있었습니다. 또한 내 while 진술 중 하나가 해제되었습니다 :) – Zzz