我想按结构的每个成员对结构数组进行排序;即,我想要 打印按结构的每个成员排序的1个列表。当 结构的成员是整数时,没问题。但其中一个成员是另一个结构数组, ,我也想按该结构的每个成员对整个混乱进行排序。下面是代码:排序struct c数组中的结构数组
#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()”比较功能。 (我正在编译C代码使用VS2010 C++(不是我的决定),因此讨厌的calloc cast。其他所有的丑是我的。)
编辑:试图简化,拙劣的比较功能。修正了。另外, 编辑:我省略了一条重要的信息:先知组对每个信仰都是一样的。所以我想要做的是按每个先知的 ,积分前体得分(然后,分别地,通过累积cassandra得分)进行排序。即:Prophet [0] cumulativeScore =(Faith [0] .Prophet [0] .precursorScore + (Faith [1] .Prophet [0] .precursorScore ... Faith [MAX_FAITH_COUNT - 1] .Prophet [0]。 precursorScore);
你的问题不明确。你希望能够在例如'faithStat.prohetStat [0] .precursorScore',以及'faithStat.prohetStat [0] .cassandraScore'和'faithStat.prohetStat [1] .precursorScore'等。 – 2012-02-26 20:10:08
是的,后者:每种信仰给予每位先知不同的分数,但他们都拥有相同的先知列表 – PaeneInsula 2012-02-26 20:56:40