Sort based on multiple things in C++

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

    the other option to an all singing all dancing comparator is to make sure your sort is a stable sort (quick sort isn't necessarily stable) and sort multiple times with different comparators each time.

    e.g.

    bool CompareAge (const record& l, const record& r)
    {
      return l.age < r.age;
    }
    
    bool CompareGender (const record& l, const record& r)
    {
      return l.gender < r.gender;
    }
    
    std::stable_sort(X, X+100, &CompareGender);
    std::stable_sort(X, X+100, &CompareAge);
    

    this will be potentially slightly slower but allow you more flexibility with the order of sorts

提交回复
热议问题