Sort based on multiple things in C++

前端 未结 5 1285
無奈伤痛
無奈伤痛 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:27

    It's better to implement comparator like this:

    bool CompareRecords(const Record& a, const Record& b)
    {
        if (a.Age < b.Age)
            return true;
        else if (a.Age > b.Age)
            return false;
    
        if (a.Gender < b.Gender)
            return true;
        else if (a.Gender > b.Gender)
            return false;
    
        if (strcmp(a.Surname, b.Surname) < 0)
            return true;
    
        return false;
    }
    

    This allows you to easy use of std::sort algorithm. Sorting itself will look like this:

    std::sort(X, X + 100, &CompareRecords);
    

    EDIT

    You may even want to implement operator < for this structure -- in that case you can normally compare two objects of Record structure with operator <. And then you don't need to add the third parameter to std::sort. And well, with that and implemented operator == you can make all possible comparizons. :)

提交回复
热议问题