I have an array of Record objects and each record object has 5 fields (first name, last name, GPA, ID number,and email). I want to sort the array based on any of the variables attributed to the object. My professor says there is a way to use one function that will sort it regardless of the variable type that is passed through. But I can't figure out a way to have one function that can sort any of those 5 variables and 3 different variable types. Meaning I can't just copy paste my sort function 5 times once for each variable. So far I can sort the array by a single value, like record[].GPA but I need a way to have like record[].x where x is whatever variable the user decides the array should we sorted by.
I tried to create a sorting function and it sorts fine but it can only handle a single variable comparison at once. For example, I have to write record[i].GPA so it compares the GPAs of the two records. However, my teacher wants it so that the function can sort based on any of the fields.
template <class T>
void sortArray(T record[]) {
bool swap = true;
while (swap) {
swap = false;
for (size_t i = 0; i < arraySize - 1; i++) {
if (record[i].GPA< record[i + 1].GPA) {
T temp = record[i];
record[i] = record[i + 1];
record[i + 1] = temp;
swap = true;
}
}
}
}
This is my sorting code as you can see I had to indicate which record variable to sort by, GPA in this case, but I need it to sort by any of the record variables depending on user selection. I'm not suppose to have multiple sort functions for each variable. I can post the rest of my code if required.