How Sort an array of objects regardless of object variable type

丶灬走出姿态 提交于 2019-12-11 21:15:18

问题


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;
}


来源:https://stackoverflow.com/questions/56402637/how-sort-an-array-of-objects-regardless-of-object-variable-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!