基于C ++中的多个事物排序 [英] Sort based on multiple things in C++
问题描述
struct Record
{
char Surname[20];
char Initial;
unsigned short int Gender; //0 = male | 1 = female
unsigned short int Age;
};
Record X[100];
如何使用Quicksort将值排序增加年龄,女性之前的男性和姓氏按字母顺序排列订购?我有一个:
How can I use Quicksort to sort the values into increasing age, with females before males and surnames in alphabetical order? I've got a:
bool CompareData(const int& A, const int& B)
{
return Records[A].Age < Records[B].Age; //this sorts by age atm
}
推荐答案
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));
}
这首先比较年龄,并返回true如果A应该出现在B之前
This compares first by age and returns true if A should appear before B based on age.
如果年龄相等,则根据性别进行比较,如果A根据性别(A是女性,B是男性)出现在B之前,则返回真。
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).
如果年龄相等,性别相等,然后比较姓氏(使用 strcmp
使用 std :: string
而不是一个字符数组,你可以使用<
A应按姓氏的字母顺序出现在B之前。
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.
这篇关于基于C ++中的多个事物排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!