How Sort an array of objects regardless of object

2019-08-25 19:20发布

问题:

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.

回答1:

You might do something like:

auto makeComp = [](auto member){
    return [=](const auto& lhs, const auto& rhs){
        return std::invoke(member, lhs) < std::invoke(member, lhs);
    }
};

switch (eMember)
{
    case EMember::FirstName: std::sort(record, record + arraySize, makeComp(T::FirstName)); break;
    case EMember::LastName:  std::sort(record, record + arraySize, makeComp(T::LastName)); break;
    case EMember::GPA:       std::sort(record, record + arraySize, makeComp(T::GPA)); break;
    case EMember::Id:        std::sort(record, record + arraySize, makeComp(T::Id)); break;
    case EMember::EMail:     std::sort(record, record + arraySize, makeComp(T::Email)); break;
}