Sort based on multiple things in C++

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

    the general pattern is:

    bool CompareData(const T& a, const T& b) 
    { 
       if (a.PrimaryCondition < b.PrimaryCondition) return true;
       if (b.PrimaryCondition < a.PrimaryCondition) return false;
    
       // a=b for primary condition, go to secondary
       if (a.SecondaryCondition < b.SecondaryCondition) return true;
       if (b.SecondaryCondition < a.SecondaryCondition) return false;
    
       // ...
    
       return false;
    } 
    

    where < indicates the "less than" in the desired sort order, you might need to use custom comparison operators for that (e.g. strcmp for strings,or reverse the < if you want to order descending) (thanks Harry for pointing this out)

    I've used < on all conditions, since that's sometimes the only comparison operation available, e.g. when you have to use an unknown data type's comparison predicate.

    [edit] Note: the last line return false handles the case where aand bare considered equal for the comparator.

    Imagine a.PrimaryCondition==b.PrimaryCondition and a.SecondaryCondition==b.SecondaryCondition - in this case, none of the previous conditions returns any value.

提交回复
热议问题