我正在尝试按结构的每个成员对结构数组进行排序;即,我想打印按结构的每个成员排序的 1 个列表。当结构的成员是整数时,没问题。但是其中一个成员是另一个结构数组,我还想按该结构的每个成员对整个混乱进行排序。这是代码:
#define PROPHET_COUNT 9000
#define MAX_FAITH_COUNT 600
typedef struct s_ProphetStat {
int precursorScore;
int cassandraScore;
int prophetId;} prophetStat;
typedef struct s_FaithStat{
int precursorScore;
int cassandraScore;
int faithId;
prophetStat ProphetStat[PROPHET_COUNT]; } faithStat;
void fauxScoringFunction(faithStat *FaithStat)
{
for (int faithIndex = 0; faithIndex < MAX_FAITH_COUNT; ++faithIndex){
for (int prophetIndex = 0; prophetIndex < PROPHET_COUNT; ++prophetIndex){
int randomNumber = rand();
FaithStat[faithIndex].ProphetStat[prophetIndex].precursorScore += randomNumber;
FaithStat[faithIndex].ProphetStat[prophetIndex].cassandraScore += randomNumber;
FaithStat[faithIndex].precursorScore += randomNumber;
FaithStat[faithIndex].cassandraScore += randomNumber; }}
}
typedef int (*compfn)(const void*, const void*);`enter code here`
int compareFaithPrecursorScores(faithStat *faithA, faithStat *faithB){
if (faithA->precursorScore > faithB->precursorScore) return 1; if (faithA->precursorScore < faithB->precursorScore) return -1; return 0; }
int compareFaithCassandraScores(faithStat *faithA, faithStat *faithB) {
if (faithA->cassandraScore > faithB->cassandraScore) return 1; if (faithA->cassandraScore < faithB->cassandraScore) return -1; return 0; }
int cannotFigureOut(...) { return 0; }
void fakemain(void)
{
faithStat *FaithStat = (faithStat *) calloc(MAX_FAITH_COUNT, sizeof(faithStat) );
fauxScoringFunction(FaithStat);
// sort by cumulative precursorScore for each faith
qsort(FaithStat, MAX_FAITH_COUNT, sizeof(faithStat *), (compfn) compareFaithPrecursorScores);
// print results();
// sort by cumulative precursorScore for each faith
qsort(FaithStat, MAX_FAITH_COUNT, sizeof(faithStat *), (compfn) compareFaithCassandraScores);
// print results()
// sort by prophet precursor score
qsort(FaithStat, MAX_FAITH_COUNT * PROPHET_COUNT, sizeof(faithStat *), (compfn) cannotFigureOut);
}
这是我正在尝试编写的“cannotFigureOut()”比较函数。(我正在使用 VS2010 C++ 编译 C 代码(不是我的决定),因此讨厌的 calloc 演员表。所有其他丑陋都是我的。)
编辑:为了简化,搞砸了比较功能。解决了这个问题。另外,编辑:我省略了一条重要信息:每种信仰的先知集都是相同的。所以我想做的是按每个先知的累积前体分数(然后分别按累积的 cassandra 分数)排序。即:Prophet[0] 累积分数 = (Faith[0].Prophet[0].precursorScore + (Faith[1].Prophet[0].precursorScore ... Faith[ MAX_FAITH_COUNT - 1].Prophet[0].precursorScore );