Sort based on multiple things in C++

前端 未结 5 1281
無奈伤痛
無奈伤痛 2020-12-08 05:11
struct Record
{
    char Surname[20];
    char Initial;
    unsigned short int Gender; //0 = male | 1 = female
    unsigned short int Age;
};
Record X[100];
<         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 05:43

    bool CompareData(const int& A, const int& B)
    {
        return (Records[A].Age < Records[B].Age) ||
               ((Records[A].Age == Records[B].Age) && (Records[A].Gender > Records[B].Gender)) || 
               ((Records[A].Age == Records[B].Age) && (Records[A].Gender == Records[B].Gender) &&
                  (strcmp(Records[A].Surname, Records[B].Surname) < 0));
    }
    

    This compares first by age and returns true if A should appear before B based on age.

    If ages are equal, it then compares by gender, and returns true if A should appear before B based on gender (A is female and B is male).

    If ages are equal and genders are equal, it then compares by surname (using strcmp, although if you had used std::string instead of a char array, you could have just used <), and returns true if A should appear before B alphabetically by surname.

提交回复
热议问题