0

I have a structure named informations,

struct informations {
    char no[12];
    char name[16];
    int exam1, exam2;
    float result;
    char letter[3];
}

I'm storing informations of students in files. I can read/write files and other things. I want to sort all students (instances of informations structure) by all properties that structure has (in this case, ["no", "name", "exam1", "exam2", "result", "letter"]).

I have a sort function, it sorts for a property, like this:

for(int i = 0; i < 99; i++) {
    for(int o = 0; o < 99; o++) {
        if(students[i].result > students[i + 1].result) {
            container = students[i];
            students[i] = students[i + 1];
            students[i + 1] = container;
        }
    }
}

The above code is, works fine for sorting all students by their result property, but I want to sort students by their all properties differently without duplicating the above code for all properties. I have ideas about to do this but I don't know how to apply these ideas into code,

  1. Store all struct properties in an array,

    string properties[6] = ["no", "name", "exam1", "exam2", "result", "letter"];

  2. Iterate over the properties array,

  3. In iteration loop, use the above sorting function by iterated property

Thanks for your helps!

1 Answers1

2

Sorry, but without reflection (which C++ does not have) it's not trivial to do.

You can reduce duplication by switching from your quadratic implementation to std::sort, then write a bunch of comparators for each sort criterion. Those ought to be as simple as return student.result < student.result, where result is whatever member you wish to compare (though this is more complex for arrays and C-strings!).

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055