I have an array of pointers that point to structs each of which have a set of variables name, id, grade, and hometown.
We are to create functions to sort that array based on those variables.
I have created a function to sort by grade, but when I run the sort and then attempt to display the array it still comes out unsorted, with my output will look like:
1 2 3
|
Bob 10170 B Bali
Al 1041 A Anchorage
Cindy 7964 C Cerritos
|
It is still unsorted by the last category, and just prints them in the order I entered them.
Here is my sortingByHometown method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
void sortbyHometown(Student *SP[])
{
for (int i = 0; i < 3; i++) {
if (SP[i]->hometown > SP[i + 1]->hometown) {
int x = SP[i]->hometown.compare(SP[i + 1]->hometown);
if (x < 0)
swap(SP[i], SP[i + 1]);
}
}
}
|
The reason I have it as i < 3 is that I am only testing when I have created 3 structs to be pointed to, just a heads up.
Also, just a heads up, this is an assignment so I have to stay in the confines of my methods and array of pointers.
Just to break down my process for getting to the sorting function too.
Initialize array of pointers to my struct (Students) size 10 (Line 27)
Create a populate fuction to populate the array with structs (This calls my initStudent which allows me to set the instance variables (Line 50)
Sort the array by hometown (Line 62, called in main on Line 30)
Here is my code, if I can get any assistance on why function isn't properly sorting that would be much appreciated, tahnks for reading!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include<iostream>
#include <stdlib.h>
#include<string>
#include<iomanip>
using namespace std;
struct Student
{
char name[20];
int SID;
char grade;
string hometown;
};
void initStudent(Student &SR);
void swap(int, int);
void display(Student*[]);
void populate(Student*[]);
void sortbyHometown(Student *SP[]);
int main() {
// Create and array of pointers to students size 10
Student *S[10];
populate(S); // Pass in array of pointers S
sortbyHometown(S);
display(S);
system("pause");
return 0;
}
void display(Student * S[]) {
for (int i = 0; i < 10; i++) {
cout << S[i]->name << setw(10) << S[i]->SID << setw(10) << S[i]->grade << setw(10) << S[i]->hometown << endl;
//s[i]->bday.display();
//cout << "\n" << s[i]->hometown << endl;
}
}
void populate(Student *S[]) {
// Can also use local[] as a parameter, they are the SAME THING
for (int i = 0; i < 3; i++) {
S[i] = new Student;
initStudent(*S[i]);
}
}
void sortbyHometown(Student *SP[])
{
for (int i = 0; i < 2; i++) {
if (SP[i]->hometown > SP[i + 1]->hometown) {
int x = SP[i]->hometown.compare(SP[i + 1]->hometown);
if (x < 0)
swap(SP[i], SP[i + 1]);
}
}
}
|