我想按結構的每個成員對結構數組進行排序;即,我想要 打印按結構的每個成員排序的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